Binary Tree Preorder Traversal - Complete Solution Guide
Binary Tree Preorder Traversal is LeetCode problem 144, a Easy level challenge. This complete guide provides step-by-step explanations, multiple solution approaches, and optimized code in python3, java, cpp, c.
Problem Statement
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: The number of nodes in the tree is in the range [0, 100] . -100 <= Node.val <= 100 Follow up: Recursive solution is trivial, could you do it iteratively?
Detailed Explanation
The problem asks you to perform a preorder traversal of a given binary tree and return the values of the nodes in the order they are visited. Preorder traversal follows the order: Root, Left Subtree, Right Subtree. The input is the root node of the binary tree, which can be empty (null). The output is a list (or array) of integers representing the node values in preorder sequence. Constraints limit the number of nodes and the range of node values.
Solution Approach
The provided solutions use an iterative approach with a stack to perform the preorder traversal. The algorithm pushes the root node onto the stack. Then, it repeatedly pops a node from the stack, adds its value to the result list, and pushes its right and then left children onto the stack (right child first to maintain preorder). This ensures that the left subtree is processed after the right subtree, following the preorder traversal order. The process continues until the stack is empty.
Step-by-Step Algorithm
- Step 1: Initialize an empty list `result` to store the preorder traversal sequence and an empty stack `stack`.
- Step 2: If the `root` is null, return the empty `result` list.
- Step 3: Push the `root` node onto the `stack`.
- Step 4: While the `stack` is not empty:
- Step 5: Pop a node from the `stack`.
- Step 6: Append the node's value to the `result` list.
- Step 7: If the node has a right child, push the right child onto the `stack`.
- Step 8: If the node has a left child, push the left child onto the `stack`.
- Step 9: Return the `result` list.
Key Insights
- Insight 1: Understanding Preorder Traversal: The core concept is the specific order of visiting nodes (Root, Left, Right).
- Insight 2: Iterative Approach using a Stack: Using a stack allows us to simulate recursion without the overhead and risk of stack overflow in the case of very deep trees.
- Insight 3: Handling Empty Tree: The code needs to gracefully handle the case where the input `root` is null (empty tree), returning an empty list.
Complexity Analysis
Time Complexity: O(n)
Space Complexity: O(n)
Topics
This problem involves: Stack, Tree, Depth-First Search, Binary Tree.
Companies
Asked at: Yahoo.