【Jianzhi 07】Rebuild Binary Tree

Method 1: Recursion: time O(n), space O(n)

Insert picture description here

answer:

  1. According to the index in the pre-order, find the corresponding position k in the middle-order
  2. Create a node, divide the left tree of the node before the k position, and the right tree of the node after the k position
  3. End condition: index to the beginning or left == right
  4. Here a map key-value pair is used to store the value and index of the middle order, and the search time complexity of the map is O(1)
class Solution {
    
    
public:
    int index = 0;  // 先序的索引
    unordered_map<int, int> board;  // 用来保存中序的值和索引
    TreeNode* build(vector<int>& preorder, int left, int right)
    {
    
    
        if (index == preorder.size() || left == right)
            return NULL;
        int pos = board[preorder[index]];
        TreeNode* root = new TreeNode(preorder[index]);
        index++;
        root->left = build(preorder, left, pos);
        root->right = build(preorder, pos + 1, right);
        return root;
    }
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) 
    {
    
    
        if (preorder.size() == 0)
            return NULL;
        // 保存中序的键值对
        for (int i = 0; i < inorder.size(); i++)
        {
    
    
            board[inorder[i]] = i;
        }
        return build(preorder, 0, preorder.size()); 
    }
};

Guess you like

Origin blog.csdn.net/qq_45691748/article/details/112408608