0
点赞
收藏
分享

微信扫一扫

剑指offer——day8【二叉树的回溯】

东方小不点 2022-04-13 阅读 35

在这里插入图片描述
题目1:树的子结构

image-20220411100552025

class Solution:
    def isSubStructure(self, A: TreeNode, B: TreeNode) -> bool:
        def dfs(A,B):
            #这里的not B表示的是如果B树被全部遍历完,说明就是A的子树
            if not B:
                return True
            if  not A or A.val!=B.val:
                return False
            #递归判断左子树和右子树
            return dfs(A.left,B.left) and dfs(A.right,B.right)
            #bool(A and B)表示的是如果A或者B一开始就是空子树,and具有短路作用
        return bool(A and B) and (dfs(A,B) or self.isSubStructure(A.left,B) or self.isSubStructure(A.right,B))
 //这是判断以当前结点为根的树与B是否相等
bool dfs(struct TreeNode*A,struct TreeNode*B)
{
    if(!B)
    {
        return true;
    }
    if(!A||A->val!=B->val)
    {
        return false;
    }

    return dfs(A->right,B->right)&&dfs(A->left,B->left);
}
bool isSubStructure(struct TreeNode* A, struct TreeNode* B){
    if(!A||!B)
    {
        return false;
    }
    //如果当前结点与B相等,或者B是A的左子树的子树,B是A的右子树的子树
    return dfs(A,B)||isSubStructure(A->left,B)||isSubStructure(A->right,B);

}

题目二:二叉树的镜像

image-20220411113438070

class Solution:
    def mirrorTree(self, root: TreeNode) -> TreeNode:
        if not root:
            return root
        
        left = self.mirrorTree(root.left)
        right = self.mirrorTree(root.right)
        root.left, root.right = right, left
        return root
#define N 1010
struct TreeNode* mirrorTree(struct TreeNode* root){
    if(root==NULL)
        return NULL;
    struct TreeNode*left=mirrorTree(root->left);
    struct TreeNode*right=mirrorTree(root->right);
    root->left=right;
    root->right=left;
    return root;
}

题目三:对称二叉树

image-20220411135919472
思路:image-20220411140803312

bool check(struct TreeNode*A,struct TreeNode*B)
{
    //如果两个都为空
    if(!A&&!B)
    {
        return true;
    }
    //如果只有一个是空
    if(!A||!B)
    {
        return false;
    }
    return A->val==B->val && check(A->left,B->right)&&check(A->right,B->left);
}

bool isSymmetric(struct TreeNode* root){
    return check(root,root);
}
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def check(L,R):
            #如果两个都为空
            if not L and not R:
                return True
            #如果只有一个为空
            if not L or not R:
                return False
            return L.val==R.val and check(L.right,R.left) and check(L.left,R.right)

        return check(root,root)
举报

相关推荐

0 条评论