LeetCode refers to Offer 07. Rebuild the binary tree

Original title link
ideas:

  1. According to the principle of preorder traversal and subsequent traversal, the array is divided, and the recursive structure is used to solve the problem of building a tree.
  2. The first element of the pre-order traversal is the root node of the tree composed of the array, and the element is found in the middle-order traversal. The left side is the left subtree of the root node, and the right side is the right subtree of the root node.
  3. Record the number of left subtree nodes in the in-order sequence, and obtain the preorder sequence of the left subtree and the right subtree sequence according to the number in the preorder sequence. In the middle sequence, the middle sequence of the left subtree and the middle sequence of the right subtree are obtained.
  4. Use recursion for these two parts.
  5. The recursive boundary is that the subtree is empty.
  6. There can be no duplicate number nodes in the tree, otherwise it will affect the location of the root node.
    Array split result
    Give the code:
/**
 * 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:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
    
    
        if(preorder.empty()) return NULL;
        TreeNode * root = new TreeNode(preorder[0]);
        int i = 0;
        
        // 去找根节点在中序遍历中的位置,该位置之前的就是左子树的节点
        // 右边是右子树的节点
        while(inorder[i] != preorder[0]){
    
    
            i++;
        }
        // 分别得到左子树的前序中序遍历数组,右子树的前序中序遍历数组
        vector<int> leftPreOrder(preorder.begin()+1,preorder.begin()+1+i);
        vector<int> leftInOrder(inorder.begin(), inorder.begin()+i);
        vector<int> rightPreOrder(preorder.begin()+1+i,preorder.end());
        vector<int> rightInOrder(inorder.begin()+1+i,inorder.end());
        
        // 对左右子树递归
        root->left =  buildTree(leftPreOrder,leftInOrder);
        root->right = buildTree(rightPreOrder,rightInOrder);
        return root;
    }
};

Guess you like

Origin blog.csdn.net/qq_43078427/article/details/109705838