# Binary Tree Preorder Traversal

Given a binary tree, return the _preorder_ traversal of its nodes' values.

Example:

``````Input:
[1,null,2,3]

1
\
2
/
3

Output:
[1,2,3]
``````

Follow up: Recursive solution is trivial, could you do it iteratively?

## Solution

#### Recursive

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
recursivePreorderTraversal(root, result);
return result;
}
void recursivePreorderTraversal(TreeNode root, List<Integer> result) {
if (root != null) {
recursivePreorderTraversal(root.left, result);
recursivePreorderTraversal(root.right, result);
}
}
}
``````

#### *LeetCode Official Solution* - Iterative using Stack

``````/* Definition for a binary tree node. */
public class TreeNode {
int val;
TreeNode left;
TreeNode right;

TreeNode(int x) {
val = x;
}
}

class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
if (root == null) {
return output;
}

while (!stack.isEmpty()) {
TreeNode node = stack.pollLast();
if (node.right != null) {
}
if (node.left != null) {
}
}
return output;
}
}
``````

#### Iterative - Using Stack

``````public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<>();
Deque<TreeNode> stack = new ArrayDeque<>();
TreeNode p = root;
while(!stack.isEmpty() || p != null) {
if(p != null) {
stack.push(p);
p = p.left;
} else {
TreeNode node = stack.pop();
p = node.right;
}
}
return result;
}
``````

#### Another Stack implementation

``````/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> result = new ArrayList<Integer>();
Stack <TreeNode> stack = new Stack <TreeNode> ();
TreeNode curr = root;
while (curr != null || !stack.isEmpty()) {
while (curr != null) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
curr = curr.right;
}
return result;
}

}
``````

#### Morris Traversal

``````class Solution {
public List<Integer> preorderTraversal(TreeNode root) {

TreeNode node = root;
while (node != null) {
if (node.left == null) {
node = node.right;
}
else {
TreeNode predecessor = node.left;
while ((predecessor.right != null) && (predecessor.right != node)) {
predecessor = predecessor.right;
}

if (predecessor.right == null) {
predecessor.right = node;
node = node.left;
}
else{
predecessor.right = null;
node = node.right;
}
}
}
return output;
}
}
``````

## Reference

https://leetcode.com/problems/binary-tree-preorder-traversal/solution/