请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
利用递归
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def symmetrical(self,left,right):
if left == None and right ==None:
return True
if left and right: # 注意,在Python中相等要用==,=是赋值的意思
return left.val == right.val and self.symmetrical(left.right,right.left) and self.symmetrical(left.left,right.right)
else:
return False
def isSymmetrical(self, pRoot):
# write code here
if pRoot == None:
return True
return self.symmetrical(pRoot.left,pRoot.right)
非递归,只需要维护一个栈即可,每次只比较一对节点。出栈的时候,相互比较的两个节点一块出栈来进行比较,有以下几种情况:
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
if pRoot == None:
return True
if pRoot.left == None and pRoot.right == None:
return True
p = pRoot.left
q = pRoot.right
stack = [p,q] # 空节点也可以入栈,为None,但是空节点就没有左右子节点了。
while stack:
p = stack.pop()
q = stack.pop()
if p == None and q == None: # 都为空继续
continue
elif p == None or q == 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