![](https://img.haomeiwen.com/i1438289/d5f078e1ff9e0ccc.png)
如题所示:对称二叉树要满足如下条件:
- 两棵子树根节点(rootA, rootB)的值相等
- rootA的左子树和rootB的右子树要对称
- rootA的右子树和rootB的左子树要对称
定义一个函数:isMirror(self, lChild, rChild),来判断两棵子树是否镜像对称。
- 递归出口:当两个节点都为空时,返回True;当一个节点为空,另一个节点不为空时,返回False。
- 递归过程:判断两个节点值是否相等;判断 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)
网友评论