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 45 46 47 48 49 50 51 52 53 54 55 56 57
| package com.leetcode;
public class ConstructBinaryTreefromPostorderandInorderTraversal106 { public static void main(String[] args) { TreeNode root = new Solution().buildTree( new int[]{9, 3, 15, 20, 7}, new int[]{9, 15, 7, 20, 3} );
}
private static class Solution { public TreeNode buildTree(int[] inorder, int[] postorder) { return constructTree(postorder, 0, postorder.length - 1, inorder, 0, inorder.length - 1); }
public TreeNode constructTree(int[] posOrder, int posS, int posE, int[] inOrder, int inS, int inE) { if (posS > posE || inS > inE) return null; else if (posS == posE) return new TreeNode(posOrder[posE]); TreeNode root = new TreeNode(posOrder[posE]); int rootPosi; for (rootPosi = inS; rootPosi <= inE; rootPosi++) { if (root.val == inOrder[rootPosi]) break; } int leftTreeLen = rootPosi - inS; root.left = constructTree(posOrder, posS, posS + leftTreeLen - 1, inOrder, inS, rootPosi - 1); root.right = constructTree(posOrder, posS + leftTreeLen, posE - 1, inOrder, rootPosi + 1, inE); return root; } }
private static class TreeNode { int val; TreeNode left; TreeNode right;
TreeNode() { }
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
}
|