二叉树是否是对称二叉树

对称的二叉树

http://nowcoder.com/practice/ff05d44dfdb04e1d83bdbdab320efbcb?tpId=13&&tqId=11211&rp=1&ru=/ta/coding-interviews&qru=/ta/coding-interviews/question-ranking

这一道题的重点是理解对称二叉树的特点。

  1. 如果根为空,那么就是一个对称的二叉树。
  2. 如果不为空就开始比较,比较左子树和右子树。
  3. 比较左子树的左节点和右子树的右节点是否对称,左子树的右节点和右子树的左节点对否对称。

我还需要更深入的理解,现在这里记录解法。

# -*- 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.isMirror(pRoot, pRoot)
    
    def isMirror(self, pRoot1, pRoot2):
        if pRoot1 is None and pRoot2 is None:
            return True
        
        if pRoot1 is None&nbs***bsp;pRoot2 is None:
            return False
        
        if pRoot1.val != pRoot2.val:
            return False
        
        return self.isMirror(pRoot1.left, pRoot2.right) and self.isMirror(pRoot1.right, pRoot2.left)


全部评论

相关推荐

04-06 11:24
已编辑
太原学院 C++
真烦好烦真烦:感觉不太对劲,这种主动加微信的一般都是坑,要小心辨别
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务