Question
Formatted question description: https://leetcode.ca/all/144.html
144 Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3},
1
\
2
/
3
return [1,2,3].
Note: Recursive solution is trivial, could you do it iteratively?
@tag-tree
Algorithm
Use stack to assist calculations. Since the order of pre-order traversal is “root-left-right”, the algorithm is:
- Push the root node onto the stack
- Loop to check whether the stack is empty. If it is not empty, take out the top element of the stack, save its value, and then check whether the right child node exists, and push it to the stack if it exists. Look at its left child node, if it exists, push it to the stack.
Code
Java
import java.util.ArrayList;
import java.util.List;
import java.util.Stack;
public class Binary_Tree_Preorder_Traversal {
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if (root == null) {
return list;
}
Stack<TreeNode> sk = new Stack<>();
sk.push(root);
while (!sk.isEmpty()) {
TreeNode current = sk.pop();
list.add(current.val); // when pushing, ensure non-null got pushed in
if (current.right != null) {
sk.push(current.right);
}
if (current.left != null) {
sk.push(current.left);
}
}
return list;
}
}
}