第十五天|二叉树

今天的题如果用recursion去做的话,相对都很容易

101. Symmetric Tree

这道题就是直接递归的同时传两个node即可

Way1:

直接遍历左子树和右子树,每次查看对应的node是不是一样的

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def same(l,r):
            if l and not r:
                return False
            if not l and r:
                return False
            if not l and not r:
                return True
            if l.val!=r.val:
                return False
            return same(l.left,r.right) and same(l.right,r.left)
        return same(root.left,root.right)

100. Same Tree

这道题就是上一题的改编

Way1:

直接遍历两个树,每次查看对应的node是不是一样的

class Solution:
    def isSameTree(self, p: Optional[TreeNode], q: Optional[TreeNode]) -> bool:
        def same(l,r):
            if not l and not r:
                return True
            if l and not r:
                return False
            if not l and r:
                return False
            if r.val!=l.val:
                return False
            return same(l.left,r.left) and same(l.right,r.right)
        return same(p,q)

572. Subtree of Another Tree

这道题还是上一题的改编,但是要注意当找到root的时候,不是要完全比较整个tree,也有可能subtree只有一个node

Way1:

每次找root,当找到的时候进行tree的比较且进行root的比较

class Solution:
    def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool:
        def same(l,r):
            if not l and not r:
                return True
            if l and not r:
                return False
            if not l and r:
                return False
            if r.val!=l.val:
                return False
            return same(l.left,r.left) and same(l.right,r.right)        
        def getroot(root,subroot):
            if not root:
                return False
            return getroot(root.left,subroot) or getroot(root.right,subroot) or same(root,subroot)
        return getroot(root,subRoot)

226. Invert Binary Tree

还是用递归的方法,每次遍历左右子树的时候直接改值,然后继续用前序遍历

Way1:

要注意潘丹条件root不是None

class Solution:
    def invertTree(self, root: Optional[TreeNode]) -> Optional[TreeNode]:
        if not root:
            return None
        root.left,root.right=root.right,root.left
        self.invertTree(root.left)
        self.invertTree(root.right)
        return root
  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值