You can greatly simplify the above with a single while loop:
Stack<Node> stack = new Stack<>(); Node current = root; while(current != null || !stack.isEmpty()){ if(current != null){ stack.push(current); current = current.left; } else if(!stack.isEmpty()) { current = stack.pop(); process(current); current = current.right; } }
Basically, the code above pushes the left branches onto the stack until it reaches the leftmost node in the branch. Then it pushes it and processes it (you can print it or do something else with it), and then it pushes the right branch onto the stack for processing, since the left branch and node itself are done.
source share