Construct Binary Tree from Inorder and Postorder Traversal(用中序和后序建树,在题目给定的函数中完成) 【leetcode】

本文详细介绍了如何利用中序和后序遍历序列构建二叉树,并通过优化内存管理避免超内存错误。重点讨论了在递归函数中释放内存的技巧,包括将vector指针强制转移为局部变量并在大括号内自动析构。此外,文章还提供了完整的代码实现和相关注意事项。

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

题目:

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

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


中序和后序建树,做烂的都,为了符合题意,我想是尽量在题目要求的函数中完成,不借助其他函数。

第一次交超内存了,因为vector的clear其实不释放内存,坑爹。

查了一下资料,有个不错的方法可以释放内存,就是吧vector的指针强制转移成局部变量,在大括号内能自动析构。

不多说了,看代码。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode *buildTree(vector<int> &inorder, vector<int> &postorder) {
        int len=inorder.size();
        if(len==0) return NULL;
        vector<int> leftin,leftpo,rightin,rightpo;
        bool flag=0;
        int p;
        for(int i=0;i<len;++i)
        {
            if(inorder[i]==postorder[len-1])
            {
                p=i;
                flag=1;
            }
            else if(flag==0)
            {
                leftin.push_back(inorder[i]);
                leftpo.push_back(postorder[i]);
            }
            else 
            {                
                rightin.push_back(inorder[i]);
                rightpo.push_back(postorder[i-1]);
            }            
        }
        TreeNode *root=new TreeNode(inorder[p]);
        {vector<int>().swap(inorder);}
        {vector<int>().swap(postorder);}
        root->left=buildTree(leftin,leftpo);
        root->right=buildTree(rightin,rightpo);        
        return root;
    }
};


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值