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 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| package com.leetcode;
import java.util.Arrays;
public class ConstructBinaryTreefromPreorderandInorderTraversal105 { public static void main(String[] args) { TreeNode root = new Solution().buildTree( new int[]{3,9,20,15,7}, new int[]{9,3,15,20,7} );
}
private static class Solution { public TreeNode buildTree(int[] preorder, int[] inorder) { return constructTree(preorder, 0, preorder.length - 1, inorder, 0, inorder.length - 1); }
public TreeNode constructTree(int[] preOrder, int preS, int preE, int[] inOrder, int inS, int inE) { if (preS > preE || inS > inE) return null; else if (preS == preE) return new TreeNode(preOrder[preS]); TreeNode root = new TreeNode(preOrder[preS]); int rootPosi; for (rootPosi = inS; rootPosi <= inE; rootPosi++) { if (root.val == inOrder[rootPosi]) break; }
int leftTreeLen = rootPosi-inS; root.left = constructTree(preOrder, preS + 1, preS+leftTreeLen, inOrder, inS, rootPosi - 1); root.right = constructTree(preOrder, preS+leftTreeLen + 1, preE, 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; } } }
|