关闭

重置二叉树

97人阅读 评论(0) 收藏 举报
分类:

问题描述:

根据二叉树的前序和后序遍历的结果,构建二叉树;

代码实现

package edu.liangman.offer;



/**
 * Created by lm on 2017/1/3.
 */
public class RebuldBinTeee {

    public static TreeNode bulid(int[] pre,int preStart,int preEnd,int[] in,
                             int inStart,int inEnd){

        if(preStart>preEnd||inStart>inEnd){
            return  null;
        }
        TreeNode root = new TreeNode(pre[preStart]);
        for(int i=inStart;i<=inEnd;i++){
            if(in[i]==pre[preStart]) {
                root.left=bulid(pre,preStart+1,i-inStart+preStart,
                        in,inStart,i-1);
                root.right= bulid(pre,i-inStart+preStart+1,preEnd,
                        in,i+1,inEnd);
            }
        }

       return root;

    }
    public static void prePrintTree(TreeNode root){
        if(root!=null){
            System.out.print(root.val+"  ");
            prePrintTree(root.left);
            prePrintTree(root.right);
        }
    }

    public static void main(String[] args){
        int[] pre ={1,2,4,7,3,5,6,8};
        int[] in  ={4,7,2,1,5,3,8,6};
        TreeNode root = bulid(pre,0,pre.length-1,in,0,in.length-1);
        prePrintTree(root);
    }


    public static class TreeNode{
        private int val;
        private TreeNode left;
        private TreeNode right;

        public TreeNode(int val) {
            this.val = val;
            this.left = null;
            this.right = null;
        }

        public TreeNode() {

        }

        public int getVal() {
            return val;
        }

        public void setVal(int val) {
            this.val = val;
        }

        public TreeNode getLeft() {
            return left;
        }

        public void setLeft(TreeNode left) {
            this.left = left;
        }

        public TreeNode getRight() {
            return right;
        }

        public void setRight(TreeNode right) {
            this.right = right;
        }
    }
}

运行结果

这里写图片描述

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:21678次
    • 积分:821
    • 等级:
    • 排名:千里之外
    • 原创:60篇
    • 转载:20篇
    • 译文:0篇
    • 评论:4条
    文章分类
    最新评论