标签:
1 /** 2 * Definition for binary tree 3 * public class TreeNode { 4 * int val; 5 * TreeNode left; 6 * TreeNode right; 7 * TreeNode(int x) { val = x; } 8 * } 9 */ 10 import java.util.*; 11 12 public class Solution { 13 public TreeNode reConstructBinaryTree(int[] pre, int[] in) { 14 if (pre == null || in == null || pre.length == 0 || in.length == 0) { 15 return null; 16 } 17 TreeNode root = construct(pre, in); 18 return root; 19 } 20 21 private TreeNode construct(int[] pre, int[] in) { 22 int length = pre.length; 23 if (length == 0) 24 return null; 25 TreeNode root = new TreeNode(pre[0]); 26 int i = 0; 27 for (; i < length; i++) { 28 if (in[i] == pre[0]) 29 break; 30 } 31 if (i == length) 32 i--; 33 int[] leftPre = Arrays.copyOfRange(pre, 1, i + 1); 34 int[] rightPre = Arrays.copyOfRange(pre, i + 1, length); 35 int[] leftIn = Arrays.copyOfRange(in, 0, i); 36 int[] rightIn = Arrays.copyOfRange(in, i + 1, length); 37 root.left = construct(leftPre, leftIn); 38 root.right = construct(rightPre, rightIn); 39 return root; 40 } 41 }
标签:
原文地址:http://www.cnblogs.com/ygh1229/p/5734533.html