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
|
class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { if(inorder.length == 0 || postorder.length == 0) return null; return build(inorder, 0, inorder.length-1, postorder, 0, postorder.length-1); } public TreeNode build(int[] inorder, int instart, int inend, int[] postorder, int poststart, int postend){ if(instart>inend || poststart > postend) return null; TreeNode root = new TreeNode(postorder[postend]); int cur = -1; for(int i=instart; i<= inend; i++){ if(root.val == inorder[i]){ cur = i; break; } } root.left = build(inorder, instart, cur-1, postorder, poststart, postend-(inend - cur)-1); root.right = build(inorder, cur+1, inend, postorder, postend-(inend - cur), postend-1); return root; } }
|