LeetCode/Top Interview 150

101. Symmetric Tree

hyunkookim 2024. 12. 11. 17:57

101. Symmetric Tree

 

https://youtu.be/Mao9uzxwvmc?si=yG0AiWstMVMAGJxt

 

# 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: Optional[TreeNode]) -> bool:
        def dfs(left, right):
            if not left and not right: # 둘다 null
                return True
            if not left or not right: # 둘 중 하나만 null
                return False

            return ((left.val == right.val) and
            dfs(left.left, right.right) and
            dfs(left.right, right.left))

        return dfs(root.left, root.right)