Sword refers to Offer's 7th day search and backtracking algorithm (simple)

The sword refers to Offer 26. The substructure of the tree

topic ideas

Continue to traverse the A tree, and judge whether it is a substructure when the point in the A tree is consistent with the root node of the B tree. Note that in the judgment function, if the B tree is traversed first, it is true, otherwise it is false when A is traversed first.

code

class Solution {
    
    
public:
    bool pan(TreeNode* A, TreeNode* B){
    
    
        if(!B)return true;
        if(!A)return false;
        //cout<<A->val<<" "<<B->val<<endl;
        if(A->val==B->val){
    
    
            return pan(A->left,B->left)&&pan(A->right,B->right);
        }else{
    
    
            return false;
        }
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
    
    
        if(!B||!A)return false;
        if((A->val==B->val)&&pan(A->left,B->left)&&pan(A->right,B->right)){
    
    
            //cout<<A->val<<endl;
            return true;
        }else{
    
    
            //cout<<A->left->val<<endl;
            return isSubStructure(A->left,B)||isSubStructure(A->right,B);
        }
    }
};

The sword refers to Offer 27. The mirror image of the binary tree

topic ideas

Swap the left subtree and the right subtree, and do it recursively

code

class Solution {
    
    
public:
    TreeNode* mirrorTree(TreeNode* root) {
    
    
        if(!root)return NULL;
        TreeNode* l = mirrorTree(root->left);
        TreeNode* r = mirrorTree(root->right);
        root->left = r;
        root->right = l;
        return root;
    }
};

Sword refers to Offer 28. Symmetric binary tree

topic ideas

Similar to the previous question, but with one more judgment function to judge whether the two tree structures are symmetric. Note that the two trees have the same structure, A->left and B->right should be compared, and A->right and B->left should be compared

code

class Solution {
    
    
public:
    bool isSymmetric(TreeNode* root) {
    
    
        if(!root)return true;
        return pan(root->left,root->right);
    }
private:
    bool pan(TreeNode* A,TreeNode* B){
    
    
        if(!A&&!B){
    
    
            return true;
        }
        if(!A||!B||A->val!=B->val){
    
    
            return false;
        }
        return pan(A->left,B->right)&&pan(A->right,B->left);
    }

};

If this article is helpful to my friends, I hope to give a like and support~ Thank you very much~

insert image description here


Guess you like

Origin blog.csdn.net/weixin_46627433/article/details/122978674