You are viewing a single comment's thread. Return to all comments →
My Java 8 solutions
Recursive approach
public static void preOrder(Node root) { if (root == null) return; System.out.print(root.data + " "); preOrder(root.left); preOrder(root.right); }
Iterative approach
public static void preOrder(Node root) { if (root == null) return; Stack<Node> stack = new Stack<>(); stack.push(root); while (!stack.isEmpty()) { Node current = stack.pop(); System.out.print(current.data + " "); if (current.right != null) { stack.push(current.right); } if (current.left != null) { stack.push(current.left); } } }
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Preorder Traversal
You are viewing a single comment's thread. Return to all comments →
My Java 8 solutions
Recursive approach
Iterative approach