Problem
Given theroot of a binary tree, return the preorder traversal of its nodes’ values.
Examples
Constraints
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
Documentation Index
Fetch the complete documentation index at: /llms.txt
Use this file to discover all available pages before exploring further.
Tested Python solution for LeetCode 144 with 15 pytest cases. Generate a practice environment with lcpy.
lcpy gen -n 144 # by problem number
lcpy gen -s binary_tree_preorder_traversal # by problem name
root of a binary tree, return the preorder traversal of its nodes’ values.
Input: root = [1,null,2,3]
Output: [1,2,3]
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [1,2,4,5,6,7,3,8,9]
Input: root = []
Output: []
Input: root = [1]
Output: [1]
from leetcode_py import TreeNode
class Solution:
# Time: O(n)
# Space: O(h) where h is the height of the tree
def preorder_traversal(self, root: TreeNode[int] | None) -> list[int]:
if not root:
return []
result: list[int] = []
stack: list[TreeNode[int]] = [root]
while stack:
node = stack.pop()
result.append(node.val)
# Push right first, then left (so left is processed first)
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
| Time | Space |
|---|---|
| O(n) | O(h) where h is the height of the tree |