publicList<Integer>preorderTraversal(TreeNode root) {List<Integer> result =newArrayList<>();Deque<TreeNode> stack =newArrayDeque<>();TreeNode p = root;while(!stack.isEmpty() || p !=null) {if(p !=null) {stack.push(p);result.add(p.val); // Add before going to children 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; } * } */classSolution {publicList<Integer> preorderTraversal(TreeNode root) {List<Integer> result =newArrayList<Integer>();Stack <TreeNode> stack =newStack <TreeNode> ();TreeNode curr = root;while (curr !=null||!stack.isEmpty()) {while (curr !=null) {result.add(curr.val);stack.push(curr); curr =curr.left; } curr =stack.pop(); curr =curr.right; }return result; }}