I have come up with this code to do level order traversal recursively for a binary search tree.
private void printLevelOrder_Recursive(Node root2) {
Queue<Node> queue = new LinkedList<Node>();
queue.add(root2);
Stack<Node> stack = new Stack<Node>();
stack.add(root2);
if(stack.isEmpty() == false) {
Node node = stack.pop();
System.out.println(node.data);
stack.addAll(printLevelOrder_Recursive_Children(node.left, node.right));
}
while(stack.isEmpty() == false) {
Node node = stack.pop();
System.out.println(node.data);
}
}
private Stack<Node> printLevelOrder_Recursive_Children(Node left, Node right) {
Stack<Node> stack = new Stack<Node>();
if (left == null && right == null) {
return stack;
}
Stack<Node> leftChildren = new Stack<Node>();
Stack<Node> rightChildren = new Stack<Node>();
if (left != null && (left.left != null || left.right != null)) {
leftChildren = printLevelOrder_Recursive_Children(left.left, left.right);
}
if (right != null && (right.left != null || right.right != null)) {
rightChildren = printLevelOrder_Recursive_Children(right.left, right.right);
}
if (rightChildren.isEmpty() == false) {
stack.addAll(rightChildren);
}
if (leftChildren.isEmpty() == false) {
stack.addAll(leftChildren);
}
if (right != null) {
stack.add(right);
}
if (left != null) {
stack.add(left);
}
return stack;
}
where Node
is:
public class Node {
public int data;
public Node left;
public Node right;
}
I looked at various implementations, but I find mine much easier. Could you please chime in with your review and thoughts?