Search code examples
javabinary-search-treebinaryfilestree-traversal

Level order traversal in a binary search tree in java


I have made 4 different traversals for my binary search tree. I am stuck at the last one which is the level order traversal and I can't get seem to find out how to do it correctly.

The main problem is that I don't know how to only search one level at a time, I only can figure out how to search either the whole left or whole right subtree.

private void preOrder(BinaryNode<AnyType> t )
    {
        if(isEmpty()){
            System.out.println("Empty");
        }
        if(t != null) {
            System.out.println(t.element);
            preOrder(t.left);
            preOrder(t.right);
        }
    }

    private void postOrder(BinaryNode<AnyType> t){

        if(isEmpty()){
            System.out.println("Empty");
        }
        if (t != null) {
            postOrder(t.left);
            postOrder(t.right);
            System.out.println(t.element);
        }
    }

    private void inOrder(BinaryNode<AnyType> t)
    {
        if(isEmpty()){
            System.out.println("Empty");
        }

        if (t != null) {
            inOrder(t.left);
            System.out.println(t.element);
            inOrder(t.right);
        }
    }

    private void levelOrder(BinaryNode<AnyType> t, int level)
    {
        if(isEmpty()){
            System.out.println("Empty");
        }

        if(height(t) == 2) {
            System.out.println(t.element);

        }else if(height(t) > 1){
            levelOrder(t.left, level );
            levelOrder(t.right, level );
        }

    }

Solution

  • This is how I did it.

    private void levelOrder(BinaryNode root) {
            if (root == null) {
                return;
            }
    
            Queue<BinaryNode> q = new LinkedList<>();
    
            // Pushing root node into the queue.
            q.add(root);
    
            // Executing loop till queue becomes
            // empty
            while (!q.isEmpty()) {
    
                BinaryNode curr = q.poll();
                System.out.print(curr.element + " ");
    
                // Pushing left child current node
                    if (curr.left != null) {
                        q.add(curr.left);
                    }
    
                    // Pushing right child current node
                    if (curr.right != null) {
                        q.add(curr.right);
                    }
                }
        }