-
标签:
树
深度优先搜索
广度优先搜索
-
难度:
简单
- 题目描述
- 我的解法
检查树的每一层(用栈保存结点)是否是对称的,检查过程中,每层最左端结点 left
和最右端结点 right
两两结对依次出栈,比较是否对称,如果不对称,返回 False
, 否则,将两者的四个子结点( left.left, left.right, right.left, right.right
)按照 (left.left, right.right,left.right,right.left
)顺讯入栈,进行下一轮的检查。
# 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):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
nodes = []
nodes.append(root.left)
nodes.append(root.right)
while(nodes):
left = nodes.pop(0)
right = nodes.pop(0)
if(not left and not right):
continue
elif not left or not right:
return False
elif left.val != right.val:
return False
else:
nodes.extend([left.left, right.right, left.right, right.left])
return True
- 其他解法
暂略。
网友评论