Binary Tree Preorder Traversal
Problem
- Given the root of a binary tree, return the preorder traversal of its nodes' values.
Reflections
Memorized at this point.
Go Solution
func preorderTraversal(root *TreeNode) []int {
var res []int
var dfs func(root *TreeNode)
dfs = func(root *TreeNode) {
if root == nil {
return
}
res = append(res, root.Val)
dfs(root.Left)
dfs(root.Right)
}
dfs(root)
return res
}Performance
- Runtime beats: 100%
- Memory beats: 32%
Complexity
- Time:
O(n) - Space:
O(n)