topic:
101. Symmetric Tree
Description:
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example
this binary tree [1,2,2,3,4,4,3] is symmetric: 1 / \ 2 2 / \ / \ 3 4 4 3 But the following [1,2,2,null,3,null,3] is not: 1 / \ 2 2 \ \ 3 3 Note: Bonus points if you could solve it both recursively and iteratively.
解题思路:1.所谓的对称,是左右相反位置的节点的值判断是否相同。
2.所有的节点对称,是可以从源头追根溯源的。
3.只要出现不同,即可返回即可,否则继续进行处理。
代码如下:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
from collections import deque
class Solution:
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
nodes_stack=[root.left,root.right]
while nodes_stack:
val_left,val_right=nodes_stack.pop(0),nodes_stack.pop(0)
if not val_left and not val_right:
continue
elif not val_left or not val_right:
return False
elif val_left.val!=val_right.val:
return False
else:
nodes_stack.extend([val_left.left,val_right.right,val_left.right,val_right.left])
return True