剑指——重建二叉树

来源:http://www.cnblogs.com/gl-developer/p/6444280.html

/** * 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==null||in==null||pre.length!=in.length||pre.length<1) return null; return construct(pre,0,pre.length-1,in,0,in.length-1); } public static TreeNode construct(int[] preOrder,int ps,int pe,int[] inOrder,int is,int ie){ //开始位置大于结束位置说明已经处理到叶节点了 if(ps>pe) return null; ///前序遍历第一个数字为当前的根节点 int value=preOrder[ps]; //index为根节点在中序遍历序列中的索引 int index=is; while(index<=ie&&inOrder[index]!=value){ index++; } //System.out.println("当前各参数的数值为->ps:"+ps+" pe:"+pe+" is:"+is+" ie:"+ie+" index:"+index+" rootValue:"+value); //如果在整个中序遍历中没有找到根节点说明输入的数据是不合法的 if(index>ie){ throw new RuntimeException("invalid input"+index); } TreeNode node=new TreeNode(value); //当前节点的左子树的个数为index-is //左子树对应的前序遍历的位置在preOrder[ps+1,ps+index-is] //左子树对应的中序遍历的位置在inOrder[is,index-1] node.left=construct(preOrder,ps+1,ps+index-is,inOrder,is,index-1); //当前节点的右子树的个数为ie-index //右子树对应的前序遍历位置在preOrder[ps+index-is+1,pe] //右子树对应的中序遍历位置在inOrder[index+1,ie] node.right=construct(preOrder,ps+index-is+1,pe,inOrder,index+1,ie); return node; } }
原文地址:https://www.cnblogs.com/Cherrylalala/p/6762646.html