Construct Binary Tree from preorder and inorder traversal
Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
It can be compared with construct Binary Tree from Inorder and postorder traversal.
The first node of the preorder traversal is the root, and because there are no duplicate values, you can use the root to divide the middle order inorder into left and right subtrees.
recursively.
/** Definition for binary tree * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * T Reenode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: TreeNode*buildtree (vector<int> &preorder, vector<int> &inorder) { returnHelper (Preorder,0, Preorder.size ()-1, Inorder,0, Inorder.size ()-1); } TreeNode*helper (vector<int> &preorder,intBegin1,intEnd1, vector<int> &inorder,intBegin2,intEnd2) { if(Begin1 >end1)returnNULL; Else if(Begin1 = =end1)return NewTreeNode (preorder[begin1]); Else { //Preorder[begin1] is the roottreenode* root =NewTreeNode (preorder[begin1]); intIND; for(Ind = begin2; ind <= END2; IND + +)) { if(Inorder[ind] = =Preorder[begin1]) Break; } // LeftRoot->left = Helper (Preorder, begin1+1, Ind-begin2+begin1, Inorder, Begin2, ind-1); // RightRoot->right = Helper (Preorder, end1-end2+ind+1, End1, Inorder, ind+1, End2); returnRoot; } }};
"Leetcode" Construct Binary Tree from preorder and inorder traversal