【力扣】28. 对称的二叉树
题目:
请实现一个函数,用来判断一棵二叉树是不是对称的。如果一棵二叉树和它的镜像一样,那么它是对称的。
我的思路:(利用栈)
用之前的颜色标记法来求解,利用左子树和右子树的对称性,判断存入当前存入结果的两个节点是否相等,如果不相等,则直接返回False
。
利用两个栈的长度是否相等、两个栈是否为空来作为跳出循环的条件。当跳出循环之后,如果两个栈都为空,那么说明左右对称,返回True
,如果有一个栈不为空,则说明左右子树深度不同,则返回False
。
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
if not root.left and not root.right:
return True
if not root.left or not root.right:
return False
left = root.left
right = root.right
white, gray = 1, 0
stack_left = [(white, left)]
stakc_right = [(white, right)]
left_val, right_val = 0, 0
while len(stack_left) == len(stack_left) and stack_left and stakc_right:
color_left, node_left = stack_left.pop()
color_right, node_right = stakc_right.pop()
if color_left == white and node_left:
stack_left.append((white, node_left.right))
stack_left.append((gray, node_left))
stack_left.append((white, node_left.left))
else:
left_val = node_left
if color_right == white and node_right:
stakc_right.append((white, node_right.left))
stakc_right.append((gray, node_right))
stakc_right.append((white, node_right.right))
else:
right_val = node_right
if left_val == right_val: #两个都为None
continue
if not left_val or not right_val: #一个为None
return False
if left_val.val != right_val.val:
return False
if len(stack_left) == 0 and len(stakc_right) == 0:
return True
return False
递归思路:
利用一个辅助函数,输入为左节点和右节点,每次判断两个节点是否满足要求:都为None
则返回True
,两个之间有一个为None
则返回False
,两个节点的值不相等的话返回False
。
代码:
class Solution:
def isSymmetric(self, root: TreeNode) -> bool:
if not root:
return True
return self.helper(root.left, root.right)
def helper(self, l, r):
if not l and not r:
return True
if not l or not r:
return False
if l.val != r.val:
return False
return self.helper(l.left, r.right) and self.helper(l.right, r.left)