101. 对称二叉树
Problem
给定一个二叉树,检查它是否是镜像对称的。
例如,二叉树 [1,2,2,3,4,4,3] 是对称的。
但是下面这个 [1,2,2,null,3,null,3] 则不是镜像对称的:
说明:
如果你可以运用递归和迭代两种方法解决这个问题,会很加分。
too young 思路
完全懵掉(´・ω・`)
感觉似乎是每一个结点的left等于对面的right???
dalao 思路
递归的方法-24ms
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
if root is None:
return True
else:
return self.isMirror(root.left, root.right)
def isMirror(self, left, right):
if left is None and right is None:
return True
if left is None or right is None:
return False
if left.val == right.val:
outpair = self.isMirror(left.left, right.right)
inpair = self.isMirror(left.right, right.left)
return outpair and inpair
return False
迭代的方法-24ms
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def isSymmetric(self, root):
if root is None:
return True
stack = [[root.left, root.right]]
while len(stack) > 0:
pair = stack.pop(0)
left = pair[0]
right = pair[1]
if left is None and right is None:
continue #pay attention
if left is None or right is None:
return False
if left.val == right.val:
stack.insert(0, [left.left, right.right])
stack.insert(0, [left.right, right.left])
else:
return False
return True