144. Binary Tree Preorder Traversal
Harsh Rajpal
Posted on January 9, 2023
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]
Example 2:
Input: root = []
Output: []
Example 3:
Input: root = [1]
Output: [1]
Constraints:
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
Solution:
Algorithm:
- Create an arraylist and a stack.
- If the node is null return the arraylist.
- Add the node to stack.
- Run a while loop till the stack is not empty.
- Pop the node and add it to the list.
- If right node is not null add it to the stack.
- If left node is not null add it to the the stack
- Return the arraylist.
Code:
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
if (root == null) {
return result;
}
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
result.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return result;
}
}
💖 💪 🙅 🚩
Harsh Rajpal
Posted on January 9, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.