Chloe Jungah Kim
Chloe Jungah Kim
A blogger who writes about everything.

[Leetcode] 144. Binary Tree Preorder Traversal

https://leetcode.com/problems/binary-tree-preorder-traversal/
[Leetcode] 144. Binary Tree Preorder Traversal

binary tree가 하나 주어졌을 때, 해당 트리의 preorder traversal의 결과를 구하는 문제

Example 1

  • Input : root = [1,null,2,3]
  • Output : [1,2,3]

Example 2

  • Input : root = []
  • Output : []

Example 3

  • Input : root = [1]
  • Output : [1]

Note

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# Definition for a binary tree node.
# class TreeNode:
#     def __init__(self, x):
#         self.val = x
#         self.left = None
#         self.right = None

class Solution:
    def preorderTraversal(self, root: TreeNode) -> List[int]:
        res = []
        def preorder(self, node: TreeNode) -> None:
            if not node :
                return            
            res.append(node.val)
            preorder(self, node.left)
            preorder(self, node.right)
        preorder(self, root)
        return res