Construct Binary Tree from preorder and inorder traversal
Given Preorder and inorder traversal of a tree, construct the binary tree.
Analysis: based on the pre-sequence traversal and the middle sequence traversal constructs a tree, the recursive solution can
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */classSolution { Public: voidBuild (intL1,intL2,intR1,intR2,Constvector<int>& Pre,Constvector<int> &inch, treenode*&root) {Root=NewTreeNode (PRE[L1]); inti; for(I=R1; i<=r2; i++) if(inch[i]==root->val) Break; if(i==R1) Root->left=nullptr; ElseBuild (L1+1, L1+I-R1,R1, I-1, Pre,inch, root->Left ); if(i==R2) Root->right=nullptr; ElseBuild (L1+i-r1+1, L2, i+1, R2, Pre,inch, root->Right ); return; } TreeNode* Buildtree (vector<int>& Preorder, vector<int>&inorder) { if(preorder.size () = =0&& inorder.size () = =0) returnnullptr; TreeNode*Root; Build (0, Preorder.size ()-1,0, Inorder.size ()-1, preorder, inorder, root); returnRoot; }};
Construct Binary Tree from preorder and inorder traversal