首先得明白题意,对称的二叉树是什么样子的?
如图所示:
判断完pRoot节点后,便判断pRoot的左子树和右子树是不是镜像的,
那么这个compare函数首先判断val是否相等,如果不相等直接False了,
如果相等得进一步递归判断,左子树left和右子树right,左子树right和右子树left是不是镜像的,以此类推进行递归。
递归结束的条件就是1-叶子节点时返回True,2-root1或root2中有一个为None,另一个不为None时返回False。
上代码:
# -*- 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
def compare(root1, root2): # 比较两个子树是否是镜像的
if root1 is None and root2 is None:
return True
if root1 is None or root2 is None:
return False
if root1.val == root2.val:
if compare(root1.left, root2.right) and compare(root1.right, root2.left):
return True
return False
return compare(pRoot.left, pRoot.right)