【力扣100】101.对称二叉树

添加链接描述

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        # 思路是递归
        
        def myfunc(tree_left,tree_right):
            if not tree_left and not tree_right:
                return True
            elif not tree_left and tree_right:
                return False
            elif tree_left and not tree_right:
                return False
            elif tree_left.val != tree_right.val:
                return False
            else:
                return myfunc(tree_left.left,tree_right.right) and myfunc(tree_right.left,tree_left.right)
            
        return myfunc(root.left,root.right)

思路:

  1. 递归,设置的递归函数的参数是两棵树
  2. 然后设置条件:都为空,左右有一个为空,左右不等
  3. 最后进行递归:注意这里的递归,你要传入的是myfunc(tree_left.left,tree_right.right) and myfunc(tree_right.left,tree_left.right)
  4. 因为这里判断的这棵树是否轴对称


非递归

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, val=0, left=None, right=None):
#         self.val = val
#         self.left = left
#         self.right = right
class Solution(object):
	def isSymmetric(self, root):
		"""
		:type root: TreeNode
		:rtype: bool
		"""
		if not root or not (root.left or root.right):
			return True
		# 用队列保存节点	
		queue = [root.left,root.right]
		while queue:
			# 从队列中取出两个节点,再比较这两个节点
			left = queue.pop(0)
			right = queue.pop(0)
			# 如果两个节点都为空就继续循环,两者有一个为空就返回false
			if not (left or right):
				continue
			if not (left and right):
				return False
			if left.val!=right.val:
				return False
			# 将左节点的左孩子, 右节点的右孩子放入队列
			queue.append(left.left)
			queue.append(right.right)
			# 将左节点的右孩子,右节点的左孩子放入队列
			queue.append(left.right)
			queue.append(right.left)
		return True

思路:

  1. 一次只向队列中存放一对元素
  2. 然后每队元素都进行判断
  3. 这个让人舒服的点是,首先踢出只有一个root节点的情况,初始化的时候就是两个节点

你可能感兴趣的:(leetcode,python,算法)