1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
|
class Solution { Map<Integer,Integer> map = new HashMap<>(); public TreeNode buildTree(int[] inorder, int[] postorder) { int n = inorder.length; for (int i = 0;i<n;i++){ map.put(inorder[i],i); } return myBuildTree(inorder,postorder,0,n-1,0,n-1); } public TreeNode myBuildTree(int[] inorder, int[] postorder,int inl,int inr,int postl,int postr){ if (inl>inr) return null; if (postr<postl) return null; int index_root = map.get(postorder[postr]);
TreeNode root = new TreeNode(postorder[postr]);
int size_right = inr-index_root;
root.left = myBuildTree(inorder,postorder,inl,index_root-1,postl,postr-size_right-1); root.right = myBuildTree(inorder,postorder,index_root+1,index_root+size_right,postr-size_right,postr-1); return root; } }
|