Leetcode—105.从前序与中序遍历序列构造二叉树【中等】

2023每日刷题(七十一)

Leetcode—105.从前序与中序遍历序列构造二叉树

Leetcode—105.从前序与中序遍历序列构造二叉树【中等】_第1张图片

实现代码

/**
 * 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> idx;

    TreeNode* buildingTree(vector<int> preorder, vector<int> inorder, int preleft, int preright, int inleft, int inright) {
        if(preleft > preright) {
            return nullptr;
        }
        // 先序对应根结点下标
        int preroot = preleft;
        // 中序对应根结点下标
        int inroot_idx = idx[preorder[preleft]];
        TreeNode* root = new TreeNode(preorder[preleft]);
        int leftTreeSize = inroot_idx - inleft;
        root->left = buildingTree(preorder, inorder, preleft + 1, preleft + leftTreeSize, inleft, inroot_idx - 1);
        root->right = buildingTree(preorder, inorder, preleft + leftTreeSize + 1, preright, inroot_idx + 1, inright);
        return root;
    }

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        int n = inorder.size();
        for(int i = 0; i < n; i++) {
            idx[inorder[i]] = i;
        }
        return buildingTree(preorder, inorder, 0, n - 1, 0, n - 1);
    }
};

运行结果

Leetcode—105.从前序与中序遍历序列构造二叉树【中等】_第2张图片

之后我会持续更新,如果喜欢我的文章,请记得一键三连哦,点赞关注收藏,你的每一个赞每一份关注每一次收藏都将是我前进路上的无限动力 !!!↖(▔▽▔)↗感谢支持!

你可能感兴趣的:(LeetCode刷题,leetcode,算法,职场和发展,经验分享,c++,二叉树,递归)