【leetcode】【105】Construct Binary Tree from Preorder and Inorder Traversal

144 篇文章 0 订阅

一、问题描述

Given preorder and inorder traversal of a tree, construct the binary tree.

二、问题分析

首先先序和中序是可以确定唯一的一棵树的。

     1       
    / \   
   2   3   
  / \ / \   
 4  5 6  7

对于上图的树来说,
index: 0 1 2 3 4 5 6
先序遍历为: 1 2 4 5 3 6 7
中序遍历为: 4 2 5 1 6 3 7
为了清晰表示,我给节点上了颜色,红色是根节点,蓝色为左子树,绿色为右子树。
可以发现的规律是:
1. 先序遍历的从左数第一个为整棵树的根节点。
2. 中序遍历中根节点是左子树右子树的分割点。


再看这个树的左子树:
先序遍历为: 2 4 5
中序遍历为: 4 2 5
依然可以套用上面发现的规律。

右子树:
先序遍历为: 3 6 7
中序遍历为: 6 3 7
也是可以套用上面的规律的。

所以这道题可以用递归的方法解决。
具体解决方法是:
通过先序遍历找到第一个点作为根节点,在中序遍历中找到根节点并记录index。
因为中序遍历中根节点左边为左子树,所以可以记录左子树的长度并在先序遍历中依据这个长度找到左子树的区间,用同样方法可以找到右子树的区间。
递归的建立好左子树和右子树就好。

三、Java AC代码

public TreeNode buildTree(int[] preorder, int[] inorder) {
        return buildTree(preorder, 0, preorder.length-1, inorder, 0, inorder.length-1);
    }
    public TreeNode buildTree(int[] preorder, int preStart, int preEnd, int[] inorder, int inStart, int inEnd){
        if(preStart > preEnd || inStart > inEnd){
            return null;
        }
        TreeNode root = new TreeNode(preorder[preStart]);
        int rootIndex = 0;
        for(int i = inStart; i <= inEnd; i++){
            if(root.val == inorder[i]){
                rootIndex = i;
                break;
            }
        }
        root.left = buildTree(preorder, preStart+1, rootIndex-inStart+preStart, inorder, inStart, rootIndex-1);
        root.right = buildTree(preorder, rootIndex-inStart+preStart+1, preEnd, inorder, rootIndex+1, inEnd);
        return root;
    }


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值