Home LeetCode - 144. Binary Tree Preorder Traversal
Post
Cancel

LeetCode - 144. Binary Tree Preorder Traversal

144. Binary Tree Preorder Traversal - Easy

문제

Given the root of a binary tree, return the preorder traversal of its nodes’ values.

제한사항

  • The number of nodes in the tree is in the range [0, 100].
  • -100 <= Node.val <= 100

입출력 예

example

1
2
3
4
5
Example 1:


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

Input: root = []
Output: []
1
2
3
4
Example 3:

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

example

1
2
3
4
5
Example 4:


Input: root = [1,2]
Output: [1,2]

example

1
2
3
4
5
Example 5:


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

풀이

  • Tree
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
/**
 * Definition for a binary tree node.
 * type TreeNode struct {
 *     Val int
 *     Left *TreeNode
 *     Right *TreeNode
 * }
 */
func preorderTraversal(root *TreeNode) []int {
    if (root == nil) {
        return []int{}
    }
    
    var res []int
    res = append(res, root.Val)
    
    left := preorderTraversal(root.Left)
    if (len(left) != 0) {
        res = append(res, left...) 
    }
    
    right := preorderTraversal(root.Right)
    if (len(right) != 0) {
        res = append(res, right...)
    }
    
    return res
}
This post is licensed under CC BY 4.0 by the author.