Description:
Given Arrays Recording ' Preorder and inorder ' traversal (problem) or ' Inorder and postorder ' (Problem 106), u need bu ILD the binary tree.
Input:
Preorder & Inorder Traversal
106. Inorder & Postorder Traversal
Output
A binary tree.
Solution:
This solution uses the algorithm "divide and conquer". Taking an example of a, we can get the root node from preorder travelsal so use inorder traversal to divide the range of left tree nodes and the right tree nodes. You can
Draw some simple instances on paper, which'll make your totally clear about the thinking.
/** Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (null), right (NULL) {} *}; */// theclassSolution { Public: voidTravel (TreeNode * *root) { if(*root) {Travel (& (*root),Left )); cout<<"Val is"<< (*root)->val<<Endl; Travel (& (*root),Right )); }} TreeNode* Createtree (vector<int>& Preorder, vector<int>& Inorder,intPresta,intPreend,intInSta,intinend) { if(Presta > Preend | | inSta > Inend)returnNULL; TreeNode*root =NewTreeNode (Preorder[presta]); intindex; for(inti = InSta; I <= inend; i + +){ if(Inorder[i] = =Preorder[presta]) {Index=i; Break; }} Root-left = Createtree (preorder, inorder, Presta +1, Presta + Index-insta, InSta, index-1); Root-right = Createtree (preorder, inorder, Presta + Index-insta +1, Preend, Index +1, Inend); returnRoot; } TreeNode* Buildtree (vector<int>& Preorder, vector<int>&inorder) {TreeNode*root = Createtree (preorder, inorder,0, Preorder.size ()-1,0, Inorder.size ()-1); TreeNode**r = &Root; //Travel (r); returnRoot; }};//106.classSolution { Public: TreeNode* Createtree (vector<int>& Inorder, vector<int>& Postorder,intInSta,intInend,intPoststa,intpostend) { if(InSta > Inend | | poststa >postend)returnNULL; TreeNode* Root =NewTreeNode (Postorder[postend]); intindex; for(inti = inend; I >= InSta; I--){ if(Postorder[postend] = =Inorder[i]) {Index=i; Break; }} Root-right = Createtree (inorder, postorder, index +1, Inend, Postend-(Inend-index), Postend-1); Root-left = Createtree (Inorder, Postorder, InSta, index-1, Poststa, Poststa + (Index-insta-1)); returnRoot; } TreeNode* Buildtree (vector<int>& Inorder, vector<int>&postorder) {TreeNode* Root = Createtree (Inorder, Postorder,0, Inorder.size ()-1,0, Postorder.size ()-1); returnRoot; }};
"Leetcode" & 106 Construct Binary Tree from (Preorder and inorder) | | (Inorder and Postorder) Traversal