construct-binary-tree-from-inorder-and-postorder-traversal
Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } public class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder==null||postorder==null||inorder.length==0||postorder.length!=postorder.length){ return null; } return buildTree(inorder,0,inorder.length-1,postorder,0,postorder.length-1); } private TreeNode buildTree(int[] inorder, int instar, int inend,int[] postorder, int poststar, int postend) { if(instar>inend||poststar>postend)return null; int value=postorder[postend]; TreeNode root=new TreeNode(value); int index; for (index =instar; index < inend&&inorder[index]!=value; index++){ } root.left=buildTree(inorder,instar,index-1,postorder,poststar,poststar+index-instar-1); root.right=buildTree(inorder,index+1,inend,postorder,poststar+index-instar,postend-1); return root; } }