给定一棵二叉树,检测它是否中心对称
例如,二叉树[1,2,2,3,4,4,3]
是对称的
1 / \ 2 2 / \ / \ 3 4 4 3
但是二叉树[1,2,2,null,3,null,3]
不是对称的
1 / \ 2 2 \ \ 3 3
注意:如果你能用递归和迭代解决这个题会很加分
1:递归,解决方式和"相同的数"(https://mp.csdn.net/postedit/82318316)的第二种解法类似
class Solution(object):
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if root == None:
return True
return self.checkTwoTree(root.left,root.right)
def checkTwoTree(self, leftTree, rightTree):
if leftTree==None and rightTree==None:
return True
if leftTree!=None and rightTree==None:
return False
if leftTree==None and rightTree!=None:
return False
if leftTree.val != rightTree.val:
return False
left = self.checkTwoTree(leftTree.left,rightTree.right)
right = self.checkTwoTree(leftTree.right,rightTree.left)
return left and right
2:迭代(有关递归和迭代的区别可以参考:https://blog.csdn.net/idaaa/article/details/78155553、https://blog.csdn.net/u011514810/article/details/52749183)
def isSymmetric(self, root):
"""
:type root: TreeNode
:rtype: bool
"""
if not root:
return True
nodeList = [root.left,root.right]
while nodeList:
symmetricLeft = nodeList.pop(0)
symmetricRight = nodeList.pop(0)
if not symmetricLeft and not symmetricRight:
continue
if not symmetricLeft or not symmetricRight:
return False
if symmetricLeft.val != symmetricRight.val:
return False
nodeList.append(symmetricLeft.left)
nodeList.append(symmetricRight.right)
nodeList.append(symmetricLeft.right)
nodeList.append(symmetricRight.left)
return True
算法题来自:https://leetcode-cn.com/problems/symmetric-tree/description/