Given a binary tree, return the preorder traversal of its nodes’ values. Can you do it without recursion?
Let’s use Stack:
- Set current node as
root
- Check if current node is
null
then return - Store current node value in the container
- Put
right
on stack - Put
left
on stack - While stack is not empty
pop
from stack into current node. Note, theleft
will be on top of stack, and will be taken first- Repeat from step 2
Implementation
/**
* @param root: A Tree
* @return: Preorder in ArrayList which contains node values.
*/
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) {
return new ArrayList<>();
}
List<Integer> rst = new ArrayList<>();
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while (!stack.empty()) {
TreeNode node = stack.pop();
rst.add(node.val);
if (node.right != null) {
stack.push(node.right);
}
if (node.left != null) {
stack.push(node.left);
}
}
return rst;
}