1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
| public TreeNode buildTree(int[] inorder, int[] postorder) { if (inorder == null || inorder.length == 0 || postorder == null || postorder.length == 0 || inorder.length != postorder.length) return null; return build(inorder, 0, inorder.length - 1, postorder, 0, postorder.length - 1); }
private TreeNode build(int[] inorder, int iStart, int iEnd, int[] postorder, int pStart, int pEnd) { if (iEnd < iStart || pEnd < pStart) return null; TreeNode root = new TreeNode(postorder[pEnd]); int idx = 0; while (inorder[iStart + idx] != postorder[pEnd]) idx++; root.left = build(inorder, iStart, iStart + idx - 1, postorder, pStart, pStart + idx - 1); root.right = build(inorder, iStart + idx + 1, iEnd, postorder, pStart + idx, pEnd - 1); return root; }
|