Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).
For example, this binary tree is symmetric:
1 / \ 2 2 / \ / \ 3 4 4 3
But the following is not:
1 / \ 2 2 \ \ 3 3
Note:
Bonus points if you could solve it both recursively and iteratively.
给定一棵二叉树,检查它是否是它自身的镜像(即:轴对称)
举个例子,这棵二叉树是对称的:
1 / \ 2 2 / \ / \ 3 4 4 3但是下面这个就不是:
1 / \ 2 2 \ \ 3 3
思路:这题用递归很好解决,开始时将左子树和右子树分别递归下去,如果第一棵树的左子树和第二棵树的右子树递归下去完全相同,同时第一棵树的右子树和第二棵树的左子树递归下去完全相同,那么这两棵树就满足对称了。如果根结点的两棵子树满足对称了,那么整棵树就是对称的了。
方法1:递归方法
def isSymmetric(self, root):
if not root: return True
return self.helper(root.left, root.right)
def helper(self, left, right):
# first make sure left and right is not none
if left and right:
if left.val == right.val:
return self.helper(left.left, right.right) and self.helper(left.right, right.left)
else:
return False
else:
# otherwise,return left == right
return left == right
方法2:迭代方法,用一个栈的数据结构储存数据,首先堆栈中加入root的左右节点(用一个列表来表示),如果栈不为空,就弹出左右节点,如果左右节点不为空,判断左右节点的值是否相等,如果相等,堆栈中压入左节点的左孩子,右节点的右孩子,左节点的右孩子,右节点的左孩子,以此类推。如果左右节点有空,判断两个节点是否相等,相等进入下一轮循环。
def isSymmetric(self, root):
if not root: return True
stack = [[root.left, root.right]]
while stack:
node1, node2 = stack.pop()
if node1 and node2: # make sure not None
if node1.val != node2.val:
return False
else:
stack.append([node1.left, node2.right])
stack.append([node1.right, node2.left])
else:
if node1 == node2:
continue
else:
return False
return True