889. 根据前序和后序遍历构造二叉树/C++

博客指出先序和后序仅反映结点间父子关系,未体现左右关系,所以通过先序和后序构造的树不唯一。

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

在这里插入图片描述
由于先序和后序只是反映了结点之间的父子关系,没有反映出左右关系。因此构造的树是不唯一的。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* construct(vector<int>& pre, int startPre, int endPre, vector<int>& post, int startPost, int endPost) {
        if(startPre>endPre || startPost>endPost) return NULL;
		
		//先序序列的第一个就是当前子树的根节点
        TreeNode* root = new TreeNode(pre[startPre]);
        //如果序列只剩下一个节点,则直接返回
        if(startPre==endPre) return root;
        
        //先序序列的第二个就是当前子树的左子节点
        //由于左子树的后序遍历的最后一个节点就是左子树的根节点,因此以`pre[startPre+1]`为界限就可以区分左右子树
        int nextval=pre[startPre+1];
        int endLeftPost;
        for(int i=startPost;i<endPost;++i){
            if(post[i]==nextval){
                endLeftPost=i;
                break;
            }
        }
        
        int lenLeft = endLeftPost-startPost;
        //如果没有右子树
        if(endLeftPost==(endPost-1))
            root->left=construct(pre,startPre+1,endPre,post,startPost,endPost-1);
        else{
            root->left=construct(pre,startPre+1,startPre+lenLeft+1,post,startPost,endLeftPost);
            root->right=construct(pre,startPre+lenLeft+2,endPre,post,endLeftPost+1,endPost-1);
        }
        return root;
    }
    
    TreeNode* constructFromPrePost(vector<int>& pre, vector<int>& post) {
        int lenPre = pre.size();
        int lenPost = post.size();
        return construct(pre,0,lenPre-1,post,0,lenPost-1);
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值