[leetcode-python3] 101. Symmetric Tree

2620 ワード

101. Symmetric Tree - python3


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
    1
   / \
  2   2
   \   \
   3    3
まず幅優先の考え方を考えてみましょう.
# 너비 우선 순회(BFS)
    def level_order_traversal(self, root):
        def _level_order_traversal(root):
            queue = [root]
            while queue:
                root = queue.pop(0)
                if root is not None:
                    print(root.val)
                    if root.left:
                        queue.append(root.left)
                    if root.right:
                        queue.append(root.right)
        _level_order_traversal(root)
でも知らなかった...皆さんHelp~~

My Answer 1: Accepted (Runtime: 36 ms / Memory Usage: 14.2 MB)

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

class Solution:
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        
        # root의 left, right를 넣기
        queue = [(root.left, root.right)]

        while queue:
            # left는 l로, right는 r로 pop
            l,r = queue.pop()
            
            # 둘다 null 이면 같으니까 continue
            if not l and not r:
                continue
            # 둘중에 하나만 null 이면 다르니까 False
            if not l or not r:
                return False
            # 둘이 값이 다르면 False
            if l.val != r.val:
                return False
            
            # 대칭이어야 하는 애들끼리 append
            queue.append((l.left, r.right))
            queue.append((r.left, l.right))
            
        return True
同志たちの援助のもとで,一連の(左,右)方式を利用する
このように対称的に比較します

Other Answer 1: (Runtime: 36 ms / Memory Usage: 14.3 MB)

# Recursion
    def isSymmetric(self, root: TreeNode) -> bool:
        if not root:
            return True
        return self.dfs(root.left, root.right)
    
    def dfs(self, p, q):
        if not p and not q:
            return True
        if None in [p,q]:
            return False
        if p.val == q.val:
            return self.dfs(p.right, q.left) and self.dfs(p.left, q.right)
これは財務を利用する方法です.
これは反復と同様で、実行時やメモリの使用も同様です.
クリスマスツリーの勉強が必要みたい^^;