Problem:
Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Hide TagsTree Array Depth-first SearchTest instructions: The binary tree is constructed by the sequential traversal sequence of the given binary tree and the subsequent traversal sequence.
Thinking:
(1) This type of problem, to give an example to find out its law. For a full two-fork tree (1,2,3,4,5,6,7), the middle sequence traversal: 4,2,5,1,6,3,7 subsequent traversal: 4,5,2,6,7,3,1
First, the root node 1 is in the last position of the subsequent traversal sequence, and then in the middle sequence to traverse the position of Find 1, before 1 is the left dial hand tree, and after 1 is the right subtree. Once you know the number of child tree nodes,
It is also possible to divide the left and right sub-trees for subsequent traversal sequences.
(2) Repeating the above procedure recursively
Code
Class Solution {public : TreeNode *buildtree (vector<int> &inorder, Vector<int> & Postorder) { if (inorder.size () = = 0) return NULL; Return make (Inorder.begin (), Inorder.end (), Postorder.begin (), Postorder.end ()); } Protected: template<class it> TreeNode *make (it pfirst,it plast,it qfirst,it qlast) { if ( Pfirst==plast) return NULL; it loc1 = qLast-1; int a = *loc1; It Loc2=find (pfirst,plast,a); int Left_size=loc2-pfirst; TreeNode *root=new TreeNode (a); Root->left=make (pfirst,loc2,qfirst,qfirst+left_size); Root->right=make (loc2+1,plast,qfirst+left_size,qlast-1); return root; } };
Leetcode | | 106. Construct Binary Tree from inorder and Postorder traversal