Construct Binary Tree from Preorder and Inorder Traversal

Oct 25, 2017

Given preorder and inorder traversal of a tree, construct the binary tree.

Note: You may assume that duplicates do not exist in the tree.

TreeNode* buildTree1(vector<int>& preorder, vector<int>& inorder) {
return bulidTreeIter(preorder.begin(),preorder.end(),inorder.begin(),inorder.end());
}
TreeNode *bulidTreeIter(vector<int>::iterator pBeg,vector<int>::iterator pEnd,vector<int>::iterator iBeg,vector<int>::iterator iEnd) {
if (pEnd == pBeg) return nullptr;
TreeNode *root = new TreeNode(*pBeg);
auto it = find(iBeg,iEnd,*pBeg);
int size = it - iBeg;
root->left = bulidTreeIter(pBeg+1,pBeg + size + 1,iBeg,it);
root->right = bulidTreeIter(pBeg+size+1,pEnd,it+1,iEnd);
return root;
}


    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {

if(preorder.size()==0)
return NULL;

stack<int> s;
stack<TreeNode *> st;
TreeNode *t,*r,*root;
int i,j,f;

f=i=j=0;
s.push(preorder[i]);

root = new TreeNode(preorder[i]);
st.push(root);
t = root;
i++;

while(i<preorder.size())
{
if(!st.empty() && st.top()->val==inorder[j])
{
t = st.top();
st.pop();
s.pop();
f = 1;
j++;
}
else
{
if(f==0)
{
s.push(preorder[i]);
t -> left = new TreeNode(preorder[i]);
t = t -> left;
st.push(t);
i++;
}
else
{
f = 0;
s.push(preorder[i]);
t -> right = new TreeNode(preorder[i]);
t = t -> right;
st.push(t);
i++;
}
}
}

return root;
}

LeetCodeLeetCodeTree

Flatten Binary Tree to Linked List

Binary Tree Level Order Traversal