【leetcode】 105. 从前序与中序遍历序列构造二叉树 106. 从中序与后序遍历序列构造二叉树

本文介绍了如何使用前序遍历和后序遍历构建二叉树的C++实现,通过`Solution`类展示了递归函数`build`用于根据给定的节点值顺序构造二叉搜索树的过程。
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> pos;
    vector<int> preorder, inorder;
    TreeNode* buildTree(vector<int>& _preorder, vector<int>& _inorder) {
        preorder = _preorder, inorder = _inorder;
        int n = inorder.size();
        for(int i = 0; i < n ; i ++) pos[inorder[i]] = i;
        return build(0, n - 1, 0, n - 1);
    }

    TreeNode* build(int a, int b, int x, int y) {
        if(a > b) return nullptr;
        auto root = new TreeNode(preorder[a]);
        int k = pos[root->val];
        root->left = build(a + 1, a + k - x, x, k - 1);
        root->right = build(a + k - x + 1, b, k + 1, y);
        return root;
    }
};
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    vector<int> inorder, postorder;
    unordered_map<int, int> pos;
    TreeNode* buildTree(vector<int>& _inorder, vector<int>& _postorder) {
        inorder = _inorder, postorder = _postorder;
        int n = inorder.size();
        for(int i = 0; i < n ; i ++) pos[inorder[i]] = i;
        return build(0, n - 1, 0, n - 1);
    }

    TreeNode* build(int a, int b, int x, int y) {
        if(a > b) return nullptr;
        auto root = new TreeNode(postorder[b]);
        int k = pos[root->val];
        root->left = build(a, k - x + a - 1, x, k - 1);
        root->right = build(k - x + a , b - 1, k + 1, y);
        return root;
    }
};
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值