对称二叉树--深度遍历与广度遍历

问题来源对称二叉树

问题描述:给定一个二叉树,检查它是否是镜像对称的。
比如,下面这个二叉树是镜像对称的;
1
/
2 2
/ \ /
3 4 4 3
而这个二叉树则不是镜像对称的。
1
/
2 2
\
3 3

例子
输入:[1,2,2,3,4,4,3]
输出:True

思路:镜像对称意味着左子树与右子树镜像对称,在遍历左子树或者右子树过程中,我们比较镜像节点即可

1. 深度遍历

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
    	# 如果该二叉树为空树,则返回True
    	if root == None: return True
    	# 如果该二叉树非空,判断是否镜像
    	def isMirror(root1, root2):
    		if (root1 == None) and (root2 == None):
    			return True
    		if (root1 == None) or (root2 == None):
    			return False
    		return (root1.val == root2.val) and isMirror(root1.left, root2.right) and isMirror(root1.right, root2.left)
   		
   		return isMirror(root.left, root.right)		

2. 广度遍历

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
    	# 二叉树为空
    	if root == None: return True
    	# 二叉树非空
    	def isMirror(root1, root2):
    		queue = []
    		queue.append(root1)
    		queue.append(root2)
    		while queue:
    			temp1 = queue.pop(0)
    			temp2 = queue.pop(0)
    			if (temp1 == None) and (temp2 == None):
    				continue
    			if (temp1 == None) or (temp2 == None):
    				return False
    			if temp1.val != temp2.val:
    				return False
    			queue.append(temp1.left)
				queue.append(temp2.right)
				queue.append(temp1.right)
				queue.append(temp2.left)
			return True
			
		return isMirror(root.left, root.right)
    
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值