Published:
Updated:

  • Reference
  • ์‹œ๊ฐ„๋ณต์žก๋„: $O(N)$ (Solution ๋‘˜ ๋‹ค)


Solution (Stack)

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


class Solution(object):
    # stack ๋ฐฉ๋ฒ• -> ํŒŒ์ด์„  ๋ฌธ๋ฒ• ๋•œ์— ํ—ค๋งด..
    # 21ms, 61.63%
    def isSymmetric(self, root):
        """
        :type root: TreeNode
        :rtype: bool
        """
        # ๋ฃจํŠธ๊ฐ€ ์—†์œผ๋ฉด ์•„๋ฌด๊ฒƒ๋„ ์กด์žฌํ•˜์ง€ ์•Š์œผ๋‹ˆ ์‚ฌ์‹ค์ƒ ๋Œ€์นญ์ž„ -> ์ฐธ
        if root is None:
            return True

        # list ํ˜•ํƒœ์˜ stack์— left, right ํ‘ธ์‹œ
        stack = [root.left, root.right]

        # stack์ด ๋นŒ ๋•Œ๊นŒ์ง€ ๊ณ„์† ๋ฐ˜๋ณต
        while stack:  # is not None <- ์ด๊ฒŒ ๋ฌธ์ œ
            left_node = stack.pop()
            right_node = stack.pop()

            # ๋‘˜ ๋‹ค null์ด๋ฉด ์ž์‹์„ ์ €์žฅํ•  ํ•„์š” X
            if left_node is None and right_node is None:
                continue

            # null ๊ฐ’์˜ ๋Œ€์นญ ํŒ๋‹จ
            if left_node is None or right_node is None:
                return False
            # ์•„๋ž˜์ฒ˜๋Ÿผ ํ•  ํ•„์š” ์—†์ด or ๋ฌธ๋ฒ•์ด ๊ฒฝ์šฐ ๋‹ค ์ฒ˜๋ฆฌํ•ด์คŒ
            # if (left_node.val is None and right_node.val is not None) or (
            #         left_node.val is not None and right_node.val is None):
            #     return False

            # ๋‹จ์ˆœ ๋ณ€์ˆ˜ ๋น„๊ต
            if left_node.val != right_node.val:
                return False

            stack.append(left_node.left)
            stack.append(right_node.right)
            stack.append(left_node.right)
            stack.append(right_node.left)

        return True

Another Solution (Recursive)

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


class Solution(object):
    # ์žฌ๊ท€ ๋ฐฉ๋ฒ•
    # 24ms, 35.79%
    def isSymmetric(self, root):
        if root is None:
            return True

        return self.check_node(root.left, root.right)

    def check_node(self, left_node, right_node):
        if left_node is None and right_node is None:
            return True

        if left_node is None or right_node is None:
            return False

        if left_node.val != right_node.val:
            return False

        return self.check_node(left_node.left, right_node.right) and self.check_node(left_node.right, right_node.left)

Leave a comment