题目描述:请实现一个函数,用来判断一颗二叉树是不是对称的。注意,如果一个二叉树同此二叉树的镜像是同样的,定义其为对称的。

Solutions

  不要被左子树右子树的禁锢太深。

# -*- 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
        return self.isSymmetricalCore(pRoot, pRoot)
    
    def isSymmetricalCore(self, pRoot1, pRoot2):
        if pRoot1 is None and pRoot2 is None:
            return True
        if pRoot1 is None or pRoot2 is None:
            return False
        if pRoot1.val != pRoot2.val:
            return False
        return self.isSymmetricalCore(pRoot1.left, pRoot2.right) and self.isSymmetricalCore(pRoot1.right, pRoot2.left)
# 运行时间:26ms
# 占用内存:5752k

References

  1. 059. 对称的二叉树