题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
思路及Python实现
递归实现
- 结合之前判断是否为镜像来做这题,图形大致如下,用递归会非常快解决!
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
def isSymmetrical(self, pRoot):
def is_mirror(left, right): # 判断是否为镜像
if left is None and right is None:
return True
elif left is None or right is None:
return False
if left.val != right.val:
return False
ret1 = is_mirror(left.left, right.right)
ret2 = is_mirror(left.right, right.left)
return ret1 and ret2
if pRoot is None:
return True
return is_mirror(pRoot.left, pRoot.right)
非递归实现
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if pRoot is None:
return True
if pRoot.left is None and pRoot.right is None:
return True
p = pRoot.left
q = pRoot.right
stack = [p, q] # 空节点也可以入栈,为None,但是空节点就没有左右子节点了。
while stack:
p = stack.pop()
q = stack.pop()
if p is None and q is None: # 都为空继续
continue
elif p is None or q is None: # 有一个不为空,另一个为空,返回False
return False
elif p.val != q.val: # 值不相等,不对称,返回False
return False
else:
# 当两个节点,都不为空,且值相等时,将两个节点对应的四个子节点
# 按照顺序依次入栈, 使之两两贴在一块,出栈的时候一块出栈,进行比较。
stack.append(p.left)
stack.append(q.right)
stack.append(p.right)
stack.append(q.left)
return True