数据结构与算法:第10周作业二:101对称的树

题目描述

在这里插入图片描述
链接:https://leetcode-cn.com/problems/symmetric-tree/

解题思路:

递归:与之前相同的树递归类似,不过是要新建一个递归函数,去比较两个结点。
迭代:用队列记录根的左右节点,看是否镜像。然后再把这两个的两个镜像放入队列,再删除最最前面的两个节点。
迭代结束的标志是1.出现不镜像的情况。2。队列为空。

代码

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if root==None:
            return True
        def compare(root1,root2):
	        if not root1 and not root2:
	            return True
	        if not root1 or not root2:
	            return False
	        if root1.val!=root2.val:
	            return False
	return compare(root1.left,root2.right) and compare(root1.right,root2.left)
class Solution(object):
    def isSymmetric(self, root):
        if not root or not (root.left or root.right):
            return True
        Queue=[root.left,root.right]
        while Queue:
            elem1=Queue.pop(0)
            elem2=Queue.pop(0)
            if not elem1 and not elem2:
                continue
            if not elem1 or not elem2:
                return False
            if elem1.val!=elem2.val:
                return False
            Queue.append(elem1.left)
            Queue.append(elem2.right)
            Queue.append(elem1.right)
            Queue.append(elem2.left)
        return True

参考链接:https://leetcode-cn.com/problems/symmetric-tree/solution/dong-hua-yan-shi-101-dui-cheng-er-cha-shu-by-user7/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值