LeetCode-101-对称二叉树(递归法)(python)

2019-08-12  本文已影响0人  JunfengsBlog
对称二叉树

如题所示:对称二叉树要满足如下条件:

  1. 两棵子树根节点(rootA, rootB)的值相等
  2. rootA的左子树和rootB的右子树要对称
  3. rootA的右子树和rootB的左子树要对称

定义一个函数:isMirror(self, lChild, rChild),来判断两棵子树是否镜像对称。

  1. 递归出口:当两个节点都为空时,返回True;当一个节点为空,另一个节点不为空时,返回False。
  2. 递归过程:判断两个节点值是否相等;判断 rootA的左子树和rootB的右子树是否对称;rootA的右子树和rootB的左子树是否对称。
    代码如下:
class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        return self.isMirror(root, root)


    def isMirror(self, lChild, rChild):
        if lChild is None and rChild is None:
            return True
        if (lChild and rChild) is None:
            return False
        return (lChild.val == rChild.val) and self.isMirror(lChild.right, rChild.left) and self.isMirror(lChild.left, rChild.right)


上一篇 下一篇

猜你喜欢

热点阅读