题目:
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
代码:
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def sym(self,left,right):
if left == None and right == None:
return True
if left and right and left.val==right.val:
return self.sym(left.left,right.right) and self.sym(left.right,right.left)
else:
return False
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root==None:
return True
return self.sym(root.left,root.right)
用到了递归的思想,根节点为空返回True;根节点的左右节点同时为空返回True;当左节点右节点均不为空而且左右节点的值相等时,就要判断左节点的左子节点和右节点的右子节点是否相等,左节点的右子节点和右节点的左子节点是否相等。若以上条件均不满足,就要返回False。