Given Inorder and Postorder traversal of a tree, construct the binary tree.
Notice
Assume that duplicates does not exist in the tree.
Example
Given inorder [1,2,3] and Postorder [1,3,2] , return a tree:
2 / 1 3
Analysis: This is a very typical recursive problem, postorder the last is root, in the inorder to find the root position, the left part of the left dial hand tree, the right part of the right subtree, the slightly troublesome part is to determine the Saozi right subtree starting index.
1 /**2 * Definition of TreeNode:3 * public class TreeNode {4 * public int val;5 * Public TreeNode left and right;6 * Public TreeNode (int val) {7 * This.val = val;8 * This.left = This.right = null;9 * }Ten * } One */ A - - Public classSolution { the /** - * @param inorder:a list of integers that inorder traversal of A tree - * @param postorder:a list of integers that postorder traversal of A tree - * @return: Root of a tree + */ - PublicTreeNode Buildtree (int[] inorder,int[] postorder) { + if(Inorder = =NULL|| Postorder = =NULL|| Postorder.length = =0|| Inorder.length! = postorder.length)return NULL; A at returnBuildtree (Inorder,0, Postorder,0, inorder.length); - - } - - PublicTreeNode Buildtree (int[] inorder,intInstart,int[] Postorder,intPoststart,intlength) { - if(Length <=0)return NULL; inTreeNode root =NewTreeNode (Postorder[poststart + Length-1]); - to intindex =FindIndex (inorder, root.val); +Root.left = Buildtree (inorder, Instart, Postorder, Poststart, index-Instart); -Root.right = Buildtree (inorder, index +1, Postorder, Poststart + (Index-instart), Length-(index-instart)-1); the * returnRoot; $ Panax Notoginseng } - the Public intFindIndex (int[] inorder,intval) { + for(inti =0; i < inorder.length; i++) { A if(Inorder[i] = =val) { the returni; + } - } $ return-1; $ } -}
Construct Binary Tree from inorder and Postorder traversal