剑指offer——重建二叉树

重建二叉树

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{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) {
        
    }
}

  

 

自己写的不对,在传入左右子树的范围那里  preLeft + i - inLeft  为什么不能直接是 i

/**
 * 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) {
        TreeNode tree = subTree(pre, 0, pre.length - 1, in, 0, in.length - 1);
        return tree;
    }
    public TreeNode subTree(int[] pre, int preLeft, int preRight, int[] in, int inLeft, int inRight){
        if(preLeft > preRight || inLeft > inRight) return null;

        TreeNode subRoot = new TreeNode(pre[preLeft]);
        for(int i = 0; i < in.length; ++i){
            if(in[i] == pre[preLeft]){
                subRoot.left = this.subTree(pre, preLeft + 1, preLeft + i - inLeft, in, inLeft, i - 1);
                subRoot.right = this.subTree(pre, preLeft + i - inLeft + 1, preRight, in, i + 1, inRight);
                break;
            }
        }
        return subRoot;
    }
}

  

posted @ 2018-03-08 21:05  SkyeAngel  阅读(127)  评论(0编辑  收藏  举报