leetcode(40)-对称二叉树
给定一个二叉树,检查它是否是镜像对称的。
https://leetcode-cn.com/problems/symmetric-tree/
# 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:
stack_left = []
stack_right = []
if root is None:return True
stack_left.append(root.left)
stack_right.append(root.right)
while len(stack_left)>0 and len(stack_right)>0:
left_top = stack_left.pop()
right_top = stack_right.pop()
if left_top is None or right_top is None:
if left_top is None and right_top is None:
continue
else:
return False
if left_top.val!=right_top.val:
return False
else:
stack_left.append(left_top.left)
stack_left.append(left_top.right)
stack_right.append(right_top.right)
stack_right.append(right_top.left)
if len(stack_right)>0 or len(stack_left)>0:
return False
return True

浙公网安备 33010602011771号