# Preorder, Inorder and Postorder Traversal Iterative Java Solution

• Postorder traversal : Binary Tree Postorder Traversal

``````public List<Integer> postorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.empty()){
root = stack.pop();
if(root.left != null) stack.push(root.left);
if(root.right != null) stack.push(root.right);
}
return list;
}
``````

Preorder traversal : Binary Tree Preorder Traversal

``````public List<Integer> preorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<>();
stack.push(root);
while(!stack.empty()){
root = stack.pop();
if(root.right != null) stack.push(root.right);
if(root.left != null) stack.push(root.left);
}
return list;
}
``````

Inorder traversal : Binary Tree Inorder Traversal

``````public List<Integer> inorderTraversal(TreeNode root) {
List<Integer> list = new ArrayList<>();
if(root == null) return list;
Stack<TreeNode> stack = new Stack<>();
while(root != null || !stack.empty()){
while(root != null){
stack.push(root);
root = root.left;
}
root = stack.pop();
root = root.right;
}
return list;
}
``````

• This post is deleted!

• comment deleted

• `ArrayList.add(0, val)` is costly, better to use `LinkedList.addFirst(val)`.

My AC Java code based on your idea of postorder traversal:

``````public class Solution {
public List<Integer> postorderTraversal(TreeNode root) {
if (root == null) return res;
Deque<TreeNode> stack = new ArrayDeque<>();
stack.push(root);
while (!stack.isEmpty()){
root = stack.pop();