This code traverses the tree, but does not use recursion, substituting it with a stack. The max size of the stack, should be the number of nodes in the last level. Is the space complexity of the following code: O(height), where height of root is 0 ?
public void preOrder() {
if (root == null) throw new IllegalStateException("the root cannot be null");
final Stack<TreeNode<E>> stack = new Stack<TreeNode<E>>();
stack.add(root);
while (!stack.isEmpty()) {
final TreeNode<E> treeNode = stack.pop();
System.out.print(treeNode.item + " ");
if (treeNode.right != null) stack.add(treeNode.right);
if (treeNode.left != null) stack.add(treeNode.left);
}
}