您的位置:首页 > Web前端

剑指offer——重建二叉树(JAVA)

2017-03-27 18:58 295 查看
/**
* Definition for binary tree
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
import java.util.Arrays;
import java.util.*;
public class Solution {
public TreeNode reConstructBinaryTree(int [] preSort,int [] inSort) {
if(preSort == null || inSort == null){
return null;
}
/**第一次没有判断长度,导致执行一半时候,数组下标越界,一直没找到原因,之前错误以为判断数组为空和数组长度为零是一样的
*/
if(preSort.length == 0 || inSort.length == 0){
return null;
}
if(preSort.length != inSort.length){
System.out.println("illegal input!");
}

//创建一个根节点
TreeNode root = new TreeNode(preSort[0]);

//System.out.println("priamry value:"+root.value);
for(int i=0; i<inSort.length; i++){
if(preSort[0] == inSort[i]){
//root.value = inSort[i];
//System.out.println(root.val);
//递归遍历
root.left = reConstructBinaryTree(Arrays.copyOfRange(preSort, 1, i+1),
Arrays.copyOfRange(inSort, 0, i));
root.right = reConstructBinaryTree(Arrays.copyOfRange(preSort, i+1, preSort.length),
Arrays.copyOfRange(inSort, i+1, inSort.length));
}
}

return root;
}
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: