LeetCode Construct Binary Tree from Preorder and Inorder Traversal

本文详细介绍了如何使用中序和前序遍历序列构建二叉树的过程,包括DFS深度优先搜索算法的应用。通过具体实例,深入浅出地解释了构建过程,帮助读者理解二叉树的构造逻辑。

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

class Solution {
public:
    TreeNode *buildTree(vector<int> &preorder, vector<int> &inorder) {
        int plen = preorder.size();
        int ilen = inorder.size();
        if (plen == 0 || ilen == 0) return NULL;
        return dfs(preorder, inorder, 0, plen, 0, ilen);
    }

    TreeNode* dfs(vector<int> &preorder, vector<int> &inorder, int ps, int pe, int is, int ie) {
        if (ps >= pe || is >= ie) return NULL;

        int rval = preorder[ps];
        int iroot= is;
        while (iroot != ie && inorder[iroot] != rval) iroot++;

        int pe_offset = (iroot - is) + ps + 1;

        TreeNode* nroot = new TreeNode(rval);

        nroot->left = dfs(preorder, inorder, ps + 1, pe_offset, is, iroot);
        nroot->right= dfs(preorder, inorder, pe_offset, pe, iroot + 1, ie);

        return nroot;
    }
};

小心驶得万年船

转载于:https://www.cnblogs.com/lailailai/p/3845071.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值