题目:输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。 代码:
/** * Definition for binary tree * public class TreeNode { * int val; * TreeNode left; * TreeNode right; * TreeNode(int x) { val = x; } * } */ public class Solution { public TreeNode reConstructBinaryTree(int [] pre,int [] in) { if(pre.length==0||in.length==0){ return null; } TreeNode tree = findRoot(pre, in); return tree; } //拆分数组 public static int[] divide(int[] arr,int start,int end){ int[] temp = new int[end-start]; int k = 0; for(int i=start;i<end;i++){ temp[k] = arr[i]; k++; } return temp; } //递归 public static TreeNode findRoot(int[] a,int[] b){ TreeNode tree = new TreeNode(a[0]); if(a.length==1){ tree.left = null; tree.right = null; return tree; } int k = 0; for(int j=0;j<b.length;j++){ if(b[j]==a[0]){ k=j; } } if(k>=1){ tree.left = findRoot(divide(a,1,k+1),divide(b, 0, k)); }else{ tree.left = null; } if(k+1<a.length){ tree.right = findRoot(divide(a,k+1,a.length),divide(b, k+1, b.length)); }else{ tree.right = null; } return tree; } }