https://leetcode.com/problems/construct-binary-tree-from-inorder-and-postorder-traversal/
Given Inorder and Postorder traversal of a tree, construct the binary tree.
Note:
Assume that duplicates does not exist in the tree.
Problem Solving Ideas:
This question and the previous question Construct Binary Tree from preorder and inorder traversal is very similar.
Here we put the following two fork tree three kinds of traversal results listed, see more clearly.
7
/ \
10 2
/ \ /
4 3 8
\ /
1 11
Preorder:7 10 4 3 1 2 8 11
Inorder:4 10 3 1 7 11 8 2
Postorder:4 1 3 10 11 8 2 7
The root node of preorder always appears in front of all nodes of its subtree, while the root node of postorder always appears behind all nodes in its subtree.
The root node of the inorder is the middle of all nodes in the Saozi right subtree.
The solution of these two problems depends on this important nature.
Recursion is actually the boundary of the array. Here we always find the root element in preorder or postorder, and then find the root position index in inorder, then the length from Instart to index is the number of nodes Zuozi, The length from index to Inend is the number of nodes in the right subtree. Then, go to preorder or postorder, and determine the extent of the Saozi right subtree node.
Then the Saozi right subtree is traversed.
/*** Definition for Binary tree * public class TreeNode {* Int. val; * TreeNode left; * TreeNode right; * TreeNode (int x) {val = x;} }*/ Public classSolution { PublicTreeNode Buildtree (int[] inorder,int[] postorder) { returnHelper (inorder, Postorder, 0, inorder.length-1, 0, Postorder.length-1); } PublicTreeNode Helper (int[] inorder,int[] Postorder,intInstart,intInend,intPoststart,intpostend) { if(Poststart > Postend | | instart >inend) { return NULL; } TreeNode Node=NewTreeNode (Postorder[postend]); intindex = 0; for(inti = Instart; I <= inend; i++){ if(Inorder[i] = =Postorder[postend]) {Index=i; Break; }} node.left= Helper (Inorder, Postorder, Instart, Index-1, Poststart, Poststart + (Index-instart)-1); Node.right= Helper (inorder, Postorder, index + 1, inend, Postend-(Inend-index), postEnd-1); returnnode; }}
Construct Binary Tree from inorder and Postorder traversal