Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Subscribe to see which companies asked this question
Idea: The last element of the subsequent traversal is the root node, through this root node, you can divide the sequence of elements to the left and right sub-tree of the other parts, to determine the establishment of the right and right subtree of the sequence traversal and subsequent traversal element subscript range, through this range recursive call function Help, continue to establish the left and right subtree, Finally, the left and right subtrees are connected to root and returned to root.
/**
* 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:
Span class= "Typ" >treenode * Buildtree ( vector <INT> & inorder vector span class= "str" ><INT> & Postorder {
if(inorder.size()==0)//节点数目为0,直接返回NULL
return NULL;
return help(inorder,0,inorder.size()-1,postorder,0,postorder.size()-1);
}
Span class= "Typ" >treenode * help ( vector <INT> & inorder int Start1 int End1 vector <INT> Postorder int Start2 int End2
if(start1>end1)//下标越界,返回NULL
return NULL;
int val = postorder[end2];//取出根节点的值
TreeNode * root =new TreeNode (val);//建立根节点
int i;
for(i=start1;i<=end1;i++)
if(inorder[i]==val)
break;//此处是根节点在中序遍历的位置
int length=i-start1;//左子树元素个数
Roo T -> left = help ( inorder start1 i - 1 postorder Start2 start2 + length - 1
Roo T -> right = help ( inorder i + 1 end1 postorder start2 + length end2 - 1
return root;
}
};
From for notes (Wiz)
106.Construct Binary Tree from inorder and Postorder traversal