解法
pre = {1,2,4,7,3,5,6,8} 根左右
in = {4,7,2,1,5,3,8,6} 左根右
根据遍历规则可以看到 中序遍历的 根的前面是左子树 根的右边是右子树 ,然后根据前序遍历可以得到根。然后我们就得到了 根的左子树的中序遍历{4,7,2}前序遍历{2,4,7} 和根的右子树的中序遍历{ 5,3,8,6},前序遍历{3,5,6,8}
然后在递归构建就OK了。
代码
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ import java.util.Arrays; public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre.length == 0 || in.length == 0 ){ return null; } TreeNode root = new TreeNode(pre[0]); for(int i=0;i<in.length;i++){ // 找到根节点 if(in[i] == pre[0]){ root.left = reConstructBinaryTree(Arrays.copyOfRange(pre,1,i+1),Arrays.copyOfRange(in,0,i)); root.right = reConstructBinaryTree(Arrays.copyOfRange(pre,i+1,pre.length),Arrays.copyOfRange(in,i+1,in.length)); break; } } return root; } }