版权声明:转载请和我说。 https://blog.csdn.net/u010929628/article/details/89310501
题目内容
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
给定一个二叉树,检查它是否是镜像对称的。
题目思路
这道题目挺简单的...就是运用递归来比较两个对称的节点。如果都不存在说明TRUE,如果有一个不存在有一个存在说明FALSE,如果数值相等继续向下比较,否则也是FALSE
程序代码
# 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 or (not root.right and not root.left):
return True
return self.check(root.left,root.right)
def check(self,left,right):
if not left and not right:
return True
if (not left and right) or (not right and left):
return False
if left.val==right.val:
return self.check(left.left,right.right) and self.check(left.right,right.left)
else:
return False