# Leetcode – Binary Tree Preorder Traversal (Java)

Analysis

Preorder binary tree traversal is a classic interview problem about trees. The key to solve this problem is to understand the following:

1. What is preorder? (parent node is processed before its children)
2. Use Stack from Java Core library

The key is using a stack to store left and right children, and push right child first so that it is processed after the left child.

Java Solution

```public class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } }   public class Solution { public ArrayList<Integer> preorderTraversal(TreeNode root) { ArrayList<Integer> returnList = new ArrayList<Integer>();   if(root == null) return returnList;   Stack<TreeNode> stack = new Stack<TreeNode>(); stack.push(root);   while(!stack.empty()){ TreeNode n = stack.pop(); returnList.add(n.val);   if(n.right != null){ stack.push(n.right); } if(n.left != null){ stack.push(n.left); }   } return returnList; } }```
Category >> Algorithms
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
```<pre><code>
String foo = "bar";
</code></pre>
```
• fishwen
• //Recursive Preorder, Inorder, PostOrder traversals.

import java.util.ArrayList;

import java.util.List;

public class TreeTraversal {

static List orderedList = new ArrayList();

public static void preOrderTraversal(TreeNode root){

if(root == null)

return;

preOrderTraversal(root.left);

preOrderTraversal(root.right);

}

public static void inOrderTraversal(TreeNode root){

if(root == null)

return;

inOrderTraversal(root.left);

inOrderTraversal(root.right);

}

public static void postOrderTraversal(TreeNode root){

if(root == null)

return;

postOrderTraversal(root.left);

postOrderTraversal(root.right);

}

public static void main(String[] args) {

TreeNode root = new TreeNode(2);

TreeNode left = new TreeNode(1);

TreeNode right = new TreeNode(3);

root.left = left;

root.right = right;

System.out.print(“nPreorder traversal of 2 1 3: “);

preOrderTraversal(root);

for(Integer i:orderedList)

System.out.print(i + ” “);

orderedList.clear();

System.out.print(“nIneorder traversal of 2 1 3: “);

inOrderTraversal(root);

for(Integer i:orderedList)

System.out.print(i + ” “);

orderedList.clear();

System.out.print(“nPostorder traversal of 2 1 3: “);

postOrderTraversal(root);

for(Integer i:orderedList)

System.out.print(i + ” “);

}
}

/*
OUTPUT:
Preorder traversal of 2 1 3: 2 1 3
Ineorder traversal of 2 1 3: 1 2 3
Postorder traversal of 2 1 3: 1 3 2
*/

• abgalphabet

it would be better to use recursion rather than imperative to solve binary tree traversal.
here is my version.

private List traversePreOrder(TreeNode root) {
if(root == null) return Collections.EMPTY_LIST;

List ordered = new ArrayList();