58.对称的二叉树
题目描述
请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。
记录
递归。
左左=右右;左右=右左;
# -*- coding:utf-8 -*-
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
def isSymmetrical(self, pRoot):
# write code here
#空树肯定对称
if pRoot is None:
return True
return self.f(pRoot.left,pRoot.right)
def f(self,left,right):
#左右子树为空,返回True,前面的都判断过了
if left is None and right is None:
return True
#左右都有,且递归的两个节点值相等
if left is not None and right is not None and left.val == right.val:
return self.f(left.left,right.right) and self.f(left.right,right.left)
else:
return False