[Algorithm] leetcode 105 constructs a binary tree from preorder and inorder traversal sequences

topic

Input the results of pre-order traversal and in-order traversal of a binary tree. Please construct the binary tree and return its root node.

Assume that the results of the input pre-order traversal and in-order traversal do not contain repeated numbers.

Example 1:

Input: preorder = [3,9,20,15,7], inorder = [9,3,15,20,7]
Output: [3,9,20,null,null,15,7]

Example 2:

Input: preorder = [-1], inorder = [-1]
Output: [-1]

limit:

0 <= 节点个数 <= 5000

answer

#include <iostream>
#include <unordered_map>
#include <vector>

using namespace std;

struct TreeNode
{
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};

class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
       for (int i = 0; i < inorder.size(); i++)
        {
            // 用中序遍历数组建立 值-下标 的映射
            value_index[inorder[i]] = i;
        }
        return recursive(preorder,0, 0, inorder.size() - 1);
    }
    TreeNode *recursive(vector<int>& pre,int pre_root, int in_left, int in_right)
    {
        if (in_left > in_right) return nullptr;
        // 将对应的 val 赋给 node 节点
        TreeNode *node = new TreeNode(pre[pre_root]);
        int in_root = value_index[pre[pre_root]];
        node->left = recursive(pre,pre_root + 1, in_left, in_root - 1);
        node->right = recursive(pre,pre_root + in_root - in_left + 1, in_root + 1, in_right);
        return node;
    }
private:
    unordered_map<int, int> value_index;
};

Guess you like

Origin blog.csdn.net/weixin_42839065/article/details/132644011