Given the root
of a binary tree, return the preorder traversal of its nodes' values.
Example 1:
Input: root = [1,null,2,3]
Output: [1,2,3]
Explanation:
Example 2:
Input: root = [1,2,3,4,5,null,8,null,null,6,7,9]
Output: [1,2,4,5,6,7,3,8,9]
Explanation:
Example 3:
Input: root = []
Output: []
Example 4:
Input: root = [1]
Output: [1]
Constraints:
[0, 100]
.-100 <= Node.val <= 100
Follow up: Recursive solution is trivial, could you do it iteratively?
## Preorder Traversal of a Binary Tree
This problem asks us to implement a preorder traversal of a binary tree. Preorder traversal visits the root node first, then recursively traverses the left subtree, and finally the right subtree.
### 1. Naive Recursive Solution
The most straightforward way to implement preorder traversal is using recursion.
```python
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorder_recursive(root):
if not root:
return []
result = [root.val]
result.extend(preorder_recursive(root.left))
result.extend(preorder_recursive(root.right))
return result
Example:
For the input root = [1, None, 2, 3]
, the recursive solution will perform the following steps:
Finally, it returns [1, 2, 3]
.
We can also implement preorder traversal iteratively using a stack.
def preorder_iterative(root):
if not root:
return []
result = []
stack = [root]
while stack:
node = stack.pop()
result.append(node.val)
# Push right child first so left child is processed first
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
Example:
For the input root = [1, None, 2, 3]
, the iterative solution will perform the following steps:
Finally, it returns [1, 2, 3]
.
[]
. Both the recursive and iterative solutions handle this case correctly.