Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Topic Analysis:
Restore the binary tree with the middle sequence traversal and subsequent traversal. Also the values of the nodes of the binary tree are not duplicated. This is good to do, we know the post-order traversal of the last node is the root node, so directly can determine the root node, and then in the sequence traversal of the array to find the value of the root node subscript index, the subscript before all the values are Zuozi nodes worth the collection, find out the size of the collection Len, The Len nodes that have arrays beginning in the post-post traversal are Zuozi. As a result, we can get an array of Zuozi traversal and subsequent traversal, so we can also know the middle sequence traversal of the right subtree and the array of subsequent traversal, so that we will be able to implement the recursive return. The code is as follows:
/** * Definition for a binary tree node. * struct TreeNode {* int val; * TreeNode *left; * TreeNode *right; * TreeNode (int x): Val (x), left (NULL) , right (NULL) {}}; */class Solution {public:treenode* BT (vector<int>&inorder,int instart,int inend,vector<int>& Postorder,int Pstart,int pend) {if (instart>inend) return NULL; treenode* root=new TreeNode (Postorder[pend]); int index; for (int i=instart;i<=inend;i++) {if (inorder[i]==root->val) {index=i; Break }} int Len=index-instart; treenode* LEFT=BT (inorder,instart,index-1,postorder,pstart,pstart+len-1); treenode* RIGHT=BT (inorder,index+1,inend,postorder,pstart+len,pend-1); root->left=left; root->right=right; return root; } treenode* Buildtree (vector<int>& inorder, vector<int>& postorder) {if (inorder.Size () ==0) return NULL; if (Inorder.size ()!=postorder.size ()) return NULL; treenode* NODE=BT (Inorder,0,inorder.size () -1,postorder,0,postorder.size ()-1); return node; } };
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Construct Binary Tree from inorder and Postorder traversal