Leetcode 144: Binary Tree Preorder Traversal

grid47
grid47
Exploring patterns and algorithms
Oct 23, 2024 5 min read

A tree with nodes glowing sequentially from root to leaf, following a smooth, glowing path.
Solution to LeetCode 144: Binary Tree Preorder Traversal Problem

You are given the root of a binary tree. The task is to return the preorder traversal of the tree. Preorder traversal means visiting the root node first, followed by the left subtree, and then the right subtree.
Problem
Approach
Steps
Complexity
Input: The input consists of a binary tree represented by its root node, where each node has a value, a left child, and a right child.
Example: Input: root = [10, null, 20, 30]
Constraints:
• The number of nodes in the tree is in the range [0, 100].
• -100 <= Node.val <= 100
Output: The output should be a list of node values representing the preorder traversal of the binary tree.
Example: Output: [10, 20, 30]
Constraints:
• The output should be a list of integers representing the node values in the correct preorder traversal order.
Goal: The goal is to return a list of node values in preorder traversal order, where each node is visited starting with the root node, followed by the left subtree, and then the right subtree.
Steps:
• 1. Start at the root of the tree.
• 2. Add the value of the current node to the result list.
• 3. Traverse the left subtree recursively.
• 4. Traverse the right subtree recursively.
Goal: The solution must handle all possible tree structures efficiently.
Steps:
• The solution must work within O(n) time complexity for n nodes in the tree.
Assumptions:
• The tree may be empty (i.e., root is null).
• The tree contains nodes with values between -100 and 100.
Input: Input: root = [10, null, 20, 30]
Explanation: The tree is: 10 -> 20 -> 30. The preorder traversal visits the root (10), then the right child (20), and its right child (30), resulting in the output [10, 20, 30].

Link to LeetCode Lab


LeetCode Solutions Library / DSA Sheets / Course Catalog
comments powered by Disqus