【LeetCode】101. Symmetric Tree

【Description】
Given a binary tree, check whether it is a mirror of itself (ie, symmetric around its center).

For example, this binary tree [1,2,2,3,4,4,3] is symmetric:

1

/
2 2
/ \ /
3 4 4 3

But the following [1,2,2,null,3,null,3] is not:

1

/
2 2
\
3 3

Follow up: Solve it both recursively and iteratively.

【Idea】
今天偷懒写个简单的。
递归比较左右节点的右左值即可,递归中发现不对称return False, 对称则继续向下比较,直到叶子节点均为空

【Solution】

# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        def judge(root1, root2):
            if not root1 and not root2: # 均null
                return True
            elif not root1 or not root2:   
                return False
            elif root1.val!=root2.val:
                return False
            else:
                return judge(root1.left, root2.right) and judge(root1.right, root2.left)
        
        if not root:
            return True
        res = judge(root.left, root.right)
        return res
image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容