首页 > 其他 > 详细

由前序遍历和中序遍历构建二叉树

时间:2018-07-09 01:00:57      阅读:271      评论:0      收藏:0      [点我收藏+]
public Node reConstructBinaryTree(int[] pre,int[] in){
        if(pre==null || in ==null){
            return null;
        }
        Node mm = reConstructBinaryTree(pre,in,0,pre.length-1,0,in.length-1);
        return mm;
    }
    public Node reConstructBinaryTree(int[] pre,int[] in,int preStart,int preEnd,int inStart,int inEnd){
        Node node = new Node(pre[preStart]);
        node.left = null;
        node.right = null;
        if(preStart == preEnd && inStart == inEnd){
            return node;
        }
        int root = 0;
        for(root = instart;root<inEnd;root++){
            if(pre[preStart] == in[root]){
                break;
            }
        }
        int leftLength = root-inStart;
        int rightLength = inEnd-root;
        if(leftLength>0){
            node.left = reConstructBinaryTree(pre,in,preStart+1,preStart+leftLength,inStart,root-1);
        }
        if(rightLength>0){
            node.right = reConstructBinaryTree(pre,in,preStart+leftLength,root+1,inEnd);
        }
        return node;
    }

 

由前序遍历和中序遍历构建二叉树

原文:https://www.cnblogs.com/yingpu/p/9281912.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!