최대 1 분 소요

Python

# 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 preorderTraversal(self, root: Optional[TreeNode]) -> List[int]:
        stack = [root]
        answer = []
        while stack:
            temp = stack.pop()
            if temp:
                answer.append(temp.val)
                stack.append(temp.left)
                stack.append(temp.right)
                
        return answer

댓글남기기