Skip to content
Related Articles

Related Articles

Print nodes of a Binary Search Tree in Top Level Order and Reversed Bottom Level Order alternately

View Discussion
Improve Article
Save Article
  • Difficulty Level : Expert
  • Last Updated : 22 Jun, 2022

Given a Binary Search Tree, the task is to print the nodes of the BST in the following order:

  • If the BST contains levels numbered from 1 to N then, the printing order is level 1, level N, level 2, level N – 1, and so on.
  • The top-level order (1, 2, …) nodes are printed from left to right, while the bottom level order (N, N-1, …) nodes are printed from right to left.

Examples:

Input:
Output: 27 42 31 19 10 14 35
Explanation:
Level 1 from left to right: 27
Level 3 from right to left: 42 31 19 10
Level 2 from left to right: 14 35

Input:
Output: 25 48 38 28 12 5 20 36 40 30 22 10

Approach: To solve the problem, the idea is to store the nodes of BST in ascending and descending order of levels and node values and print all the nodes of the same level alternatively between ascending and descending order. Follow the steps below to solve the problem:

  • Initialize a Min Heap and a Max Heap to store the nodes in ascending and descending order of level and node values respectively.
  • Perform a level order traversal on the given BST to store the nodes in the respective priority queues.
  • Print all the nodes of each level one by one from the Min Heap followed by the Max Heap alternately.
  • If any level in the Min Heap or Max Heap is found to be already printed, skip to the next level.

Below is the implementation of the above approach:

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Structure of a BST node
struct node {
    int data;
    struct node* left;
    struct node* right;
};
 
// Utility function to create a new BST node
struct node* newnode(int d)
{
    struct node* temp
        = (struct node*)malloc(sizeof(struct node));
    temp->left = NULL;
    temp->right = NULL;
    temp->data = d;
    return temp;
}
 
// Function to print the nodes of a
// BST in Top Level Order and Reversed
// Bottom Level Order alternatively
void printBST(node* root)
{
    // Stores the nodes in descending order
    // of the level and node values
    priority_queue<pair<int, int> > great;
 
    // Stores the nodes in ascending order
    // of the level and node values
 
    priority_queue<pair<int, int>,
                   vector<pair<int, int> >,
                   greater<pair<int, int> > >
        small;
 
    // Initialize a stack for
    // level order traversal
    stack<pair<node*, int> > st;
 
    // Push the root of BST
    // into the stack
    st.push({ root, 1 });
 
    // Perform Level Order Traversal
    while (!st.empty()) {
 
        // Extract and pop the node
        // from the current level
        node* curr = st.top().first;
 
        // Stores level of current node
        int level = st.top().second;
        st.pop();
 
        // Store in the priority queues
        great.push({ level, curr->data });
        small.push({ level, curr->data });
 
        // Traverse left subtree
        if (curr->left)
            st.push({ curr->left, level + 1 });
 
        // Traverse right subtree
        if (curr->right)
            st.push({ curr->right, level + 1 });
    }
 
    // Stores the levels that are printed
    unordered_set<int> levelsprinted;
 
    // Print the nodes in the required manner
    while (!small.empty() && !great.empty()) {
 
        // Store the top level of traversal
        int toplevel = small.top().first;
 
        // If the level is already printed
        if (levelsprinted.find(toplevel)
            != levelsprinted.end())
            break;
 
        // Otherwise
        else
            levelsprinted.insert(toplevel);
 
        // Print nodes of same level
        while (!small.empty()
               && small.top().first == toplevel) {
            cout << small.top().second << " ";
            small.pop();
        }
 
        // Store the bottom level of traversal
        int bottomlevel = great.top().first;
 
        // If the level is already printed
        if (levelsprinted.find(bottomlevel)
            != levelsprinted.end()) {
            break;
        }
        else {
            levelsprinted.insert(bottomlevel);
        }
 
        // Print the nodes of same level
        while (!great.empty()
               && great.top().first == bottomlevel) {
            cout << great.top().second << " ";
            great.pop();
        }
    }
}
 
// Driver Code
int main()
{
    /*
    Given BST
 
                                25
                              /     \
                            20      36
                           /  \      / \
                          10   22   30 40
                         /  \      /   / \
                        5   12    28  38 48
    */
 
    // Creating the BST
    node* root = newnode(25);
    root->left = newnode(20);
    root->right = newnode(36);
    root->left->left = newnode(10);
    root->left->right = newnode(22);
    root->left->left->left = newnode(5);
    root->left->left->right = newnode(12);
    root->right->left = newnode(30);
    root->right->right = newnode(40);
    root->right->left->left = newnode(28);
    root->right->right->left = newnode(38);
    root->right->right->right = newnode(48);
 
    // Function Call
    printBST(root);
 
    return 0;
}


Java




// Java program for the above approach
import java.io.*;
import java.util.*;
 
class GFG {
 
  // Structure of a BST node
  static class node {
    int data;
    node left;
    node right;
  }
 
  //Structure of pair (used in PriorityQueue)
  static class pair{
    int x,y;
    pair(int xx, int yy){
      this.x=xx;
      this.y=yy;
    }
  }
 
  //Structure of pair (used in Stack)
  static class StackPair{
    node n;
    int x;
    StackPair(node nn, int xx){
      this.n=nn;
      this.x=xx;
    }
  }
 
  // Utility function to create a new BST node
  static node newnode(int d)
  {
    node temp = new node();
    temp.left = null;
    temp.right = null;
    temp.data = d;
    return temp;
  }
 
  //Custom Comparator for pair class to sort
  //elements in increasing order
  static class IncreasingOrder implements Comparator<pair>{
    public int compare(pair p1, pair p2){
      if(p1.x>p2.x){
        return 1;
      }else{
        if(p1.x<p2.x){
          return -1;
        }else{
          if(p1.y>p2.y){
            return 1;
          }else{
            if(p1.y<p2.y){
              return -1;
            }else{
              return 0;
            }
          }
        }
      }
    }
  }
 
  // Custom Comparator for pair class to sort
  // elements in decreasing order
  static class DecreasingOrder implements Comparator<pair>{
    public int compare(pair p1, pair p2){
      if(p1.x>p2.x){
        return -1;
      }else{
        if(p1.x<p2.x){
          return 1;
        }else{
          if(p1.y>p2.y){
            return -1;
          }else{
            if(p1.y<p2.y){
              return 1;
            }else{
              return 0;
            }
          }
        }
      }
    }
  }
 
  // Function to print the nodes of a
  // BST in Top Level Order and Reversed
  // Bottom Level Order alternatively
  static void printBST(node root)
  {
    // Stores the nodes in descending order
    // of the level and node values
    PriorityQueue<pair> great = new PriorityQueue<>(new DecreasingOrder());
 
    // Stores the nodes in ascending order
    // of the level and node values
 
    PriorityQueue<pair> small = new PriorityQueue<>(new IncreasingOrder());
 
    // Initialize a stack for
    // level order traversal
    Stack<StackPair> st = new Stack<>();
 
    // Push the root of BST
    // into the stack
    st.push(new StackPair(root,1));
 
    // Perform Level Order Traversal
    while (!st.isEmpty()) {
 
      // Extract and pop the node
      // from the current level
      StackPair sp = st.pop();
      node curr = sp.n;
 
      // Stores level of current node
      int level = sp.x;
 
      // Store in the priority queues
      great.add(new pair(level,curr.data));
      small.add(new pair(level,curr.data));
 
      // Traverse left subtree
      if (curr.left!=null)
        st.push(new StackPair(curr.left,level+1));
 
      // Traverse right subtree
      if (curr.right!=null)
        st.push(new StackPair(curr.right,level+1));
    }
 
    // Stores the levels that are printed
    HashSet<Integer> levelsprinted = new HashSet<>();
 
    // Print the nodes in the required manner
    while (!small.isEmpty() && !great.isEmpty()) {
 
      // Store the top level of traversal
      int toplevel = small.peek().x;
 
      // If the level is already printed
      if (levelsprinted.contains(toplevel))
        break;
 
      // Otherwise
      else
        levelsprinted.add(toplevel);
 
      // Print nodes of same level
      while (!small.isEmpty() && small.peek().x == toplevel) {
        System.out.print(small.poll().y + " ");
      }
 
      // Store the bottom level of traversal
      int bottomlevel = great.peek().x;
 
      // If the level is already printed
      if (levelsprinted.contains(bottomlevel)) {
        break;
      }
      else {
        levelsprinted.add(bottomlevel);
      }
 
      // Print the nodes of same level
      while (!great.isEmpty() && great.peek().x == bottomlevel) {
        System.out.print(great.poll().y + " ");
      }
    }
  }
 
  public static void main (String[] args) {
    /*
        Given BST
 
                                    25
                                  /     \
                                20      36
                               /  \      / \
                              10   22   30 40
                             /  \      /   / \
                            5   12    28  38 48
        */
 
    // Creating the BST
    node root = newnode(25);
    root.left = newnode(20);
    root.right = newnode(36);
    root.left.left = newnode(10);
    root.left.right = newnode(22);
    root.left.left.left = newnode(5);
    root.left.left.right = newnode(12);
    root.right.left = newnode(30);
    root.right.right = newnode(40);
    root.right.left.left = newnode(28);
    root.right.right.left = newnode(38);
    root.right.right.right = newnode(48);
 
    // Function Call
    printBST(root);
  }
}
 
// This code is contributed by shruti456rawal


Output:

25 48 38 28 12 5 20 36 40 30 22 10

Time Complexity: O(V log(V)), where V denotes the number of vertices in the given Binary Tree
Auxiliary Space: O(V)


My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!