Given the root of a binary tree, return the preorder traversal of its nodes’ values.
A preorder traversal of a binary tree is a type of depth-first traversal that visits nodes in the following order:
Example:
Input: root = [1,null,2,3]
Output: [1,2,3]
None
.To perform a preorder traversal, we can use either an iterative approach or a recursive approach.
None
, return.We’ll go with the iterative approach for this solution.
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def preorderTraversal(root: TreeNode):
if root is None:
return []
stack = [root]
result = []
while stack:
node = stack.pop()
result.append(node.val)
# Push right child first so that left is processed first
if node.right:
stack.append(node.right)
if node.left:
stack.append(node.left)
return result
Time Complexity: O(n), where n is the number of nodes in the binary tree. Each node is visited exactly once.
Space Complexity: O(n) in the worst case for the stack if the tree is completely unbalanced (resembling a linked list). In the average case (balanced tree), the space complexity will be O(log n). The result list will also take O(n) space.
This solution efficiently handles the preorder traversal of a binary tree using an iterative approach.
Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?