剑指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; } }
相关文章推荐
- 剑指Offer:面试题6——重建二叉树(java实现)
- 剑指offer之重建二叉树(java)
- 剑指offer面试题6:重建二叉树(Java实现)
- 剑指offer-重建二叉树 java实现
- Java 剑指offer之二叉树的重建
- 剑指offer 重建二叉树 java实现
- 剑指offer-重建二叉树(java版)
- 剑指Offer面试题6(Java版):重建二叉树
- 剑指offer 面试题6 重建二叉树 java版答案
- 剑指offer面试题6 重建二叉树(java)
- 【剑指offer-Java版】06重建二叉树
- 剑指Offer面试题6:重建二叉树 Java实现
- 剑指offer|面试题6:重建二叉树(Java实现)
- 剑指offer面试题6 重建二叉树(java实现)
- 剑指offer面试题6 重建二叉树(java)
- <剑指offer 面试题7-2>重建二叉树 Java
- 【剑指offer——JAVA实现】重建二叉树(含思路解答示意图)
- 剑指Offer面试题6(Java版):重建二叉树
- 剑指offer----重建二叉树---java实现
- 剑指offer:重建二叉树(java)