6 重建二叉树

1、递归的写法:

public class Solution {
    public TreeNode reConstructBinaryTree(int [] pre,int plow,int phigh,int [] in,int ilow,int ihigh) {
        if(plow == phigh)
            return new TreeNode(pre[plow]);
        if(plow > phigh || ilow > phigh)
            return null;

        int key = pre[plow];
        TreeNode root = new TreeNode(key);
        //找到前序遍历中的节点在中序遍历中的位置
        int i;
        for(i=ilow;i<=ihigh;i++){
            if(in[i] == key){
                break;
            }
        }

        int leftTreeSize = i - ilow;

        root.left = reConstructBinaryTree(pre,plow+1,plow+leftTreeSize,in,ilow,i-1);

        root.right = reConstructBinaryTree(pre,plow+leftTreeSize+1,phigh,in,i+1,ihigh);
        return root;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
       return reConstructBinaryTree(pre,0,pre.length-1,in,0,in.length-1);       
    }
}

有人找i值使用了HashMap来存储!
注意:终结条件!
if(plow == phigh)
return new TreeNode(pre[plow]);
if(plow > phigh || ilow > phigh)
return null;

尤其是if(plow > phigh || ilow > phigh)条件,数组下标+1或者-1或者其他变化的时候,肯定不会在你期望的地方结束的。

public class Solution {
     public int indexOfIn(int head,int[] in){
        int len = in.length;
        for(int i=0;i<len;i++)
            if(head == in[i])
                return i;
        return -1;
    }
    public TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        int len = in.length;
        if(len == 0)
            return null;
        int head = pre[0];
        TreeNode root = new TreeNode(head);

        int headIndex = indexOfIn(head,in);//3
        int leftLen = headIndex;//3
        int rightLen = len - 1 - headIndex;//4
        int[] leftPre = new int[leftLen];
        int[] rightPre = new int[rightLen];
        for(int i=0;i<leftLen;i++){//3
            leftPre[i] = pre[i+1];
        }
        for(int i=0;i<rightLen;i++){//4
            rightPre[i] = pre[i+headIndex+1];
        }

        int[] leftIn = new int[leftLen];
        int[] rightIn = new int[rightLen];
        for(int i=0;i<leftLen;i++){
            leftIn[i] = in[i];
        }
        for(int i=0;i<rightLen;i++){
            rightIn[i] = in[i+headIndex+1];
        }
        root.left = reConstructBinaryTree(leftPre,leftIn);
        root.right = reConstructBinaryTree(rightPre,rightIn);
        return root;
    }
}

这样,最后的判断就简单了,只需要判断数组的长度是不是0即可!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值