[Prove safety the offer] Reconstruction binary (obtained according to the preceding binary tree in Sequence Number)

Reconstruction of a binary tree

topic

Before entering a binary preorder traversal order and results, rebuild the binary tree.

note:

  • Value for each node in the binary tree are different from each other;
  • And input preorder traversal preorder certain legal;

Sample

Given:
a preorder traversal is: [3, 9, 20, 15, 7]
inorder traversal is: [9, 3, 15, 20, 7]

Returns: [3, 9, 20, null, null, 15, 7, null, null, null, null]
returns the binary tree as follows:
        3
      / \
     920
           / \
         157

answer

Solving idea is as follows:

  1. The preorder traversal to find the root, i.e. a first number sequence preorder traversal
  2. In order to find the root node traversal sequence index (unordered_map advance with each record corresponding to the number sequence preorder subscript)
  3. Preorder number in the sequence, the root index and the left column of the left subtree, the root index number of columns to the right of the right subtree i.e., recursive subtree standard range according to achievements
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    unordered_map<int, int> umap;
    int pre;
    
    TreeNode* recursionTree(vector<int>& preorder, vector<int>& inorder, int l, int r) {
        if (l > r) return NULL;
        // 找到并建立根节点
        TreeNode* root = new TreeNode(preorder[pre]);
        // 在中序遍历序列中确定根节点的下标
        int mid = umap[preorder[pre ++]];
        // 递归构建左子树
        root->left = recursionTree(preorder, inorder, l, mid-1);
        // 递归构建右子树
        root->right = recursionTree(preorder, inorder, mid+1, r);
        return root;
    }
    
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        for (int i = 0; i < inorder.size(); i ++) 
            umap[inorder[i]] = i;
        return recursionTree(preorder, inorder, 0, inorder.size()-1);
    }
};
Published 10 original articles · won praise 0 · Views 565

Guess you like

Origin blog.csdn.net/weixin_44922845/article/details/104100813