Given Preorder and inorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Analyse:we can see from the pic above so the left of the pivot element of preorder sequence in inorder sequence is the The left subtree of this element, and the right part are the right subtree of this element.
Runtime:64ms.
Recursion
1 /**2 * Definition for a binary tree node.3 * struct TreeNode {4 * int val;5 * TreeNode *left;6 * TreeNode *right;7 * TreeNode (int x): Val (x), left (null), right (null) {}8 * };9 */Ten classSolution { One Public: Atreenode* Buildtree (vector<int>& Preorder, vector<int>&inorder) { - if(preorder.size () = =0)returnNULL; - returnBuild (Preorder,0, Preorder.size ()-1, Inorder,0, Inorder.size ()-1); the } -treenode* Build (vector<int>& Preorder,intPreleft,intPreright, vector<int>& Inorder,intInleft,intinright) { - if(Preleft > Preright)returnNULL;//When would this case appear - +treenode* root =NewTreeNode (Preorder[preleft]); - if(Preleft = = preright)returnRoot; + A //find the position of root (Preorder[preleft]) in inorder sequence at intindex =0; - for(; index < inorder.size (); index++){ - if(Inorder[inleft + index] = = Preorder[preleft]) Break; - } - -Root->left = Build (preorder, Preleft +1, Preleft + index, inorder, inleft, Inleft + index-1); inRoot->right = Build (preorder, Preleft + index +1, Preright, inorder, Inleft + index +1, inright); - to returnRoot; + } -};
Construct Binary Tree from preorder and inorder traversal