《剑指offer》(JAVA版)——重建二叉树

15 篇文章 0 订阅
15 篇文章 0 订阅
一、题目描述

输入某二叉树的前序遍历和中序遍历的结果,请重建出该二叉树。假设输入的前序遍历和中序遍历的结果中都不含重复的数字。例如输入前序遍历序列{1,2,4,7,3,5,6,8}和中序遍历序列{4,7,2,1,5,3,8,6},则重建二叉树并返回。

输入 :某二叉树的前序遍历和中序遍历的结果数组
输出 :二叉树的根结点

牛客NOWCODER

二、思路分析

在二叉树的前序遍历中,第一个数字是树的根结点;在中序遍历中,左子树的结点位于根结点的左边,右子树的结点位于根结点的右边。

三、实现代码
/**
 * @AUTHOR:0416
 * @DESCRIPTION:
 * @DATE:2019/10/17
 **/
public class RebuildBinaryTree {

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

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

    public static TreeNode reConstructBinaryTree(int [] pre,int [] in) {
        if (pre == null || in == null) {
            return null;
        }
        return RebulidBinaryTree(pre, in, 0, 0, pre.length);
    }

    public static TreeNode RebulidBinaryTree(int[] pre, int[] in, int preIndex, int inIndex,
                                         int count){
        if (count <= 0) {
            return null;
        }
        TreeNode root = new TreeNode(pre[preIndex]);
        int i = 0;
        for (; i < count; i++) {
            if (in[i + inIndex] == root.val) {
                break;
            }
        }
        //建立左子树
        root.left =
                RebulidBinaryTree(pre, in, preIndex + 1, inIndex, i);
        //建立右子树
        root.right = RebulidBinaryTree(pre, in,
                preIndex + i + 1, inIndex + i + 1, count - i - 1);

        return root;
    }


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


    public static void main(String[] args) {
        int[] preOrder = {1,2,4,7,3,5,6,8};
        int[] inOrder = {4,7,2,1,5,3,8,6};
        TreeNode root = reConstructBinaryTree(preOrder, inOrder);
        printPostOrder(root);
    }

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值