剑指Offer-第7天 搜索与回溯算法(简单)


第一题

题目链接:https://leetcode.cn/problems/shu-de-zi-jie-gou-lcof/

个人题解:递归判断即可,先写一个判断函数,再在函数里面递归调用即可。

代码:

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

运行截图:

第二题

题目链接:https://leetcode.cn/problems/er-cha-shu-de-jing-xiang-lcof/

个人题解:先创建左子树和右子树,然后左指向右,右指向左。

代码:

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

运行截图:

第三题

题目链接:https://leetcode.cn/problems/dui-cheng-de-er-cha-shu-lcof/

个人题解:比上一题多了一个判断罢了

代码:

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

运行截图:

相关