《剑指offer》006-重建二叉树

题目:输入前序和中序,重建二叉树。(假设前序和中序不含重复数字)。

public class ConstructBiTree {
    public static void main(String[] args) {
        // TODO Auto-generated method stub
        int[] pre = {1,2,4,7,3,5,6,8};
        int[] in = {4,7,2,1,5,3,8,6};
//      int[] pre = {1,2};
//      int[] in = {2,1};
        if((pre.length < 1) || (pre.length != in.length)){
            System.out.println("Invalid input, cannot find a tree.");
        }
        ConstructBiTree c = new ConstructBiTree();
        BiTreeNode root = c.construct(pre, in);
        System.out.print("preorder: ");
        c.t(root);
    }

    private void t(BiTreeNode node) {
        // TODO Auto-generated method stub
         if(node != null){
                System.out.print(node.data + " ");
                t(node.left);
                t(node.right);
            }
    }
    public BiTreeNode construct(int[] pre,int[] in){
        if(pre.length == 0 || pre.length != in.length){
            return null;
        }
        return constructCore(pre, 0, pre.length-1, in, 0, in.length-1);
    }
    public BiTreeNode constructCore(int[] pre, int p, int q, int[] in, int i, int j){
        BiTreeNode root = new BiTreeNode(pre[p]);
        root.left = null;
        root.right = null;
        if(p == q){
            if(i == j && pre[p] == in[i]){
                return root;
            }else{
                System.out.println("Invalid input, cannot find a tree.");
                //throws exception
            }
        }
        int rootInorder = i;
        while(pre[p] != in[rootInorder] && rootInorder <= j){
            rootInorder++;
        }
        if(rootInorder == j && pre[p] != in[rootInorder]){
            System.out.println("Invalid input, cannot find a tree.");
            //throws exception
        }
        int leftLength = rootInorder - i;
        int leftPreorderEnd = p +leftLength;
        if(leftLength > 0){
            root.left = constructCore(pre, p+1, leftPreorderEnd, in, i, rootInorder-1);
        }
        if(q - p - leftLength > 0){
            root.right = constructCore(pre, leftPreorderEnd+1, q, in, rootInorder+1, j);
        }
        return root;
    }
    class BiTreeNode{
        int data;
        BiTreeNode left;
        BiTreeNode right;
        public BiTreeNode(int data){
            this.data = data;
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值