Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
This topic is to give you a tree in the middle sequence traversal and post-order traversal, let you show this tree. One can assume that there are no duplicate elements in the tree.
When the problem is finished, it is recommended to do the 105th question, similar to the question.
Analysis: The basic idea of this solution is that we have two arrays, namely in and post. The post-traversal hint Posr[end] (that is, the last element of the posts array) is the root node. After that we can look for post[end] in. Let's say we find in[5]. Now we can know in[5] is the root node, then in[0] to In[4] is the left subtree, in[6] to the end is the right sub-tree. We can then process the array recursively.
The code below, where the code has defeated 100% C # submitter:
/** Definition for a binary tree node. * public class TreeNode {* public int val, * public TreeNode left; public TreeNode right; * Public TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Buildtree (int[] inorder,int[] postorder) { returnBinaryTree (Postorder. length-1,0, Inorder. length-1, Inorder,postorder); } PublicTreeNode BinaryTree (intPostend,intInstart,intInend,int[] inorder,int[] postorder) { if(postend<0|| Instart>inend)return NULL; intinindex=0; TreeNode Root=NewTreeNode (Postorder[postend]); for(inti=instart;i<=inend;i++) { if(inorder[i]==Postorder[postend]) {Inindex=i; Break; }} root.left=binarytree (postend-(Inend-inindex)-1, instart,inindex-1, Inorder,postorder); Root.right=binarytree (postend-1, inindex+1, Inend,inorder,postorder); returnRoot; }}
The most critical thing is to determine the function's actual parameters, it must not be mistaken.
Root.left=binarytree (postend-(Inend-inindex) -1,instart,inindex-1,inorder,postorder);
The Inend-inindex represents the number of elements in the right subtree, and the element should be subtracted in order to obtain the last of the left subtree.
C # solution Leetcode 106. Construct Binary Tree from inorder and Postorder traversal