Skip to content

Instantly share code, notes, and snippets.

@churehill
Last active April 22, 2016 16:58
Show Gist options
  • Save churehill/66b52264049b7114f66dcd0fb5e70493 to your computer and use it in GitHub Desktop.
Save churehill/66b52264049b7114f66dcd0fb5e70493 to your computer and use it in GitHub Desktop.
test github highlist
// Definition for a binary tree node.
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
public:
// Construct Binary Tree from Preorder and Inorder Traversal
// 由先序和中序重建二叉树
TreeNode* buildTreeInPre(vector<int>& preorder, vector<int>& inorder) {
if (preorder.empty())
return NULL;
stack<TreeNode *> st;
int pt = 0, it = 0;
bool flag = false;
TreeNode *pnode = new TreeNode(preorder[pt++]), *root = pnode;
st.push(pnode);
while (pt < preorder.size() || it < inorder.size()) {
if (!st.empty() && st.top()->val == inorder[it]) {
pnode = st.top(); st.pop();
it ++;
flag = true;
}
else {
TreeNode* cur = new TreeNode(preorder[pt++]);
if (flag) {
pnode->right = cur;
flag = false;
}
else {
st.top()->left = cur;
}
st.push(cur);
}
}
return root;
}
// Construct Binary Tree from Inorder and Postorder Traversal
// 由后序和中序重建二叉树
TreeNode* buildTreeInPost(vector<int>& inorder, vector<int>& postorder) {
if (inorder.empty())
return NULL;
stack<TreeNode *> st;
int pt = postorder.size() - 1, it = pt;
TreeNode *pnode = new TreeNode(postorder[pt--]), *root = pnode;
st.push(pnode);
bool flag = false;
while (pt >= 0 || it >= 0) {
if (!st.empty() && st.top()->val == inorder[it]) {
pnode = st.top(); st.pop();
flag = true;
it --;
}
else {
TreeNode* cur = new TreeNode(postorder[pt--]);
if(flag) {
pnode->left = cur;
flag = false;
}
else {
st.top()->right = cur;
}
st.push(cur);
}
}
return root;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment