LeetCode 105 Construct Binary Tree from Preorder and Inorder Traversal

本文详细介绍了如何通过给定的前序遍历和中序遍历数组来构建二叉树的过程,包括理解核心概念、递归实现以及关键步骤解析。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目


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

Note:
You may assume that duplicates do not exist in the tree.

从前序遍历数组和中序遍历数组 ,得到二叉树。


思路


我直接做没有想出思路,看了大牛的博客 http://blog.youkuaiyun.com/fightforyourdream/article/details/16914595 的代码才理解了意思。虽然有点事后诸葛,但是应该这样考虑。

a 首先应该拿出具体的例子来看,比如 preorder 1,2,4,5,3 inorder 4,2,5,1,3

b 肯定是用递归来做,那么肯定是对root来做

c 发现preorder中root就是第一个元素,相应的在inorder中,root把其他元素分成两半,一半是root.left,一半是root.right

d 能够想到上面那步,代码也就能写出来了。


代码


public class Solution {
    public TreeNode buildTree(int[] preorder, int[] inorder) {
        if(preorder.length==0||inorder.length==0||preorder.length!=inorder.length){
            return null;
        }
        int n = preorder.length;
        return useme(preorder,inorder,0,n-1,0,n-1);
    }
    
    public TreeNode useme(int[] preorder,int[] inorder, int prestart,int preend,int instart,int inend){
       
        TreeNode root = new TreeNode(preorder[prestart]);
        int rootIndex;
        for(rootIndex=instart;rootIndex<inend;rootIndex++){
            if(inorder[rootIndex]==preorder[prestart]){
                break;
            }
        }
        int len = rootIndex - instart;
        if(rootIndex>instart){
            root.left = useme(preorder,inorder,prestart+1,prestart+len,instart,rootIndex-1);
        }
        if(rootIndex<inend){
            root.right = useme(preorder,inorder,prestart+len+1,preend,rootIndex+1,inend);
        }
        return root;
    }
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值