美文网首页
LeetCode-101-对称二叉树(递归法)(python)

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

作者: JunfengsBlog | 来源:发表于2019-08-12 21:02 被阅读0次
对称二叉树

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

  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)


相关文章

网友评论

      本文标题:LeetCode-101-对称二叉树(递归法)(python)

      本文链接:https://www.haomeiwen.com/subject/tzupjctx.html