[LeetCode] 101. Symmetric Tree

김민우·2023년 3월 13일
0

알고리즘

목록 보기
156/189

- Problem

101. Symmetric Tree

- 내 풀이 1 (DFS)

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        def is_mirror(left: TreeNode, right: TreeNode) -> bool:
            if not left and not right:
                return True
            if not left or not right:
                return False
            return left.val == right.val and is_mirror(left.left, right.right) and is_mirror(left.right, right.left)

        return is_mirror(root.left, root.right)

- 결과


- 내 풀이 2 (BFS)

class Solution:
    def isSymmetric(self, root: Optional[TreeNode]) -> bool:
        q = deque([(root.left, root.right)])
        
        while q:
            l, r = q.popleft()
            
            if not l and not r:
                continue
                
            if not l or not r or l.val != r.val:
                return False
            
            q.append((l.left, r.right))
            q.append((l.right, r.left))
            
        return True

- 결과

profile
Pay it forward.

0개의 댓글