The sword refers to the reconstruction of the offer binary tree - c++ implementation

Question: Input the results of preorder traversal and inorder traversal of a binary tree, please reconstruct the binary tree. It is assumed that the results of the input preorder traversal and inorder traversal do not contain duplicate numbers. For example, input the preorder traversal sequence {1,2,4,7,3,5,6,8} and the inorder traversal sequence {4,7,2,1,5,3,8,6}, then rebuild the binary tree and return.

Idea: The first node of the preorder traversal is the root node. The root node divides the numbers into two groups in the inorder traversal. The left subtree is the left subtree, and the right subtree is the right subtree. Find the root node, recursively.

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    TreeNode* reConstructBinaryTree(vector<int> pre,vector<int> vin) {
        if(pre.size()<=0||vin.size()<=0||pre.size()!=vin.size())
            return nullptr;
        vector<int> left_pre,right_pre,left_vin,right_vin;
        TreeNode *head=new TreeNode(pre[0]);
        int gen=0;
        for(int i=0;i<vin.size();i++)
        {
            if(vin[i]==pre[0])
            {
                gen=i;
                break;
            }
        }
        
        for(int i=0;i<gen;i++)
        {
            left_vin.push_back(vin[i]);
            left_pre.push_back(pre[i+1]);
        }
        for(int i=gen+1;i<vin.size();i++)
        {
            right_vin.push_back(vin[i]);
            right_pre.push_back(pre[i]);
        }
        head->left=reConstructBinaryTree(left_pre,left_vin);
        head->right=reConstructBinaryTree(right_pre,right_vin);
        return head;
    }
};


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325478305&siteId=291194637