[LeetCode] 106. Construct Binary Tree from Inorder and Postorder Traversal

本文介绍了一种使用后序遍历和中序遍历序列构建二叉树的方法。通过递归地构建左右子树,在确保正确处理后序遍历下标的基础上,实现了二叉树的构建。

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

Construct Binary Tree from Inorder and Postorder Traversal

Given inorder and postorder traversal of a tree, construct the binary tree.
Note:
You may assume that duplicates do not exist in the tree.
For example, given

inorder = [9,3,15,20,7]
postorder = [9,15,7,20,3]
Return the following binary tree:
3
/ \
9 20
/ \
15 7

解析

递归构建左右子树即可。但是在后序遍历的时候要注意下标问题。

代码

class Solution {
public:
    TreeNode* buildTree(vector<int>& inorder, vector<int>& postorder) {
        if(postorder.empty() || inorder.empty())
            return NULL;
        int val = postorder[postorder.size()-1];
        int size = inorder.size();
        TreeNode* root = new TreeNode(val);
        vector<int> leftpost;
        vector<int> rightpost;
        vector<int> leftin;
        vector<int> rightin;
        int index;
        for(int i=0;i<size;i++){
            if(inorder[i] == val){
                index = i;
                break;
            }
        }
        for(int i=0;i<index;i++){
            leftin.push_back(inorder[i]);
            leftpost.push_back(postorder[i]);
        }
        for(int i=index+1;i<size;i++){
            rightin.push_back(inorder[i]);
            rightpost.push_back(postorder[i-1]); //postorder的下标需要思考一下,不要理所当然。
        }

        root->left = buildTree(leftin, leftpost);
        root->right = buildTree(rightin, rightpost);
        return root;        
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值