/** * 用先序数组和中序数组重建一棵树 */ public class ConstructBinaryTreeFromPreorderAndInorderTraveral { public static class TreeNode { public int val; public TreeNode left; public TreeNode right; TreeNode(int val) { this.val = val; } } public static TreeNode buildTree(int[] pre, int[] in) { if (pre == null || in == null || pre.length != in.length) { return null; } return f(pre, 0, pre.length - 1, in, 0, in.length - 1); } //有一棵树,先序结果是pre[l1...r1],中序in[l2...r2] //建成一棵树返回头节点 public static TreeNode f(int[] pre, int l1, int r1, int[] in, int l2, int r2) { if (l1 > r1) {//左树为空或者佑树为空 return null; } TreeNode head = new TreeNode(pre[l1]); if (l1 == r1) { return head; } int find = l2; for (; in[find] != pre[l1]; find++) ; head.left = f(pre, l1 + 1, l1 + (find - l2), in, l2, find - 1); head.right = f(pre, l1 + (find - l2) + 1, r1, in, find + 1, r2); return head; } }