Largest number possible by arranging node values at each level

Given a Binary Tree with positive values at each node, the task is to print the maximum number that can be formed by arranging nodes at each level.

Examples:

Input:                4
                    /   \
                   2    59
                  / \   / \
                 1   3  2  6
Output: 
Maximum number at 0'th level is 4
Maximum number at 1'st level is 592
Maximum number at 2'nd level is 6321


Input:           1
               /   \
              2     3
             / \     \
            4   5     8
                     /  \
                    6    79  
Output:
Explanation :
The maximum number at the 0'th level is 1
The maximum number at 1'st level is 32
The maximum number at 2'nd level is 854
The maximum number at 3'rd level is 796

Approach:

  • Traverse all nodes at each level one by one using Level Order Traversal.
  • Store their values in a vector of strings.
  • Sort the vector using Comparison method to generate greatest number possible.
  • Display the number and repeat the procedure for all levels.

Below code is the implementation of the above approach:

C++

filter_none

edit
close

play_arrow

link
brightness_4
code

// C++ program to find maximum number
// possible from nodes at each level.
#include <bits/stdc++.h>
using namespace std;
  
/* A binary tree node representation */
struct Node {
    int data;
    struct Node *left, *right;
};
  
int myCompare(string X, string Y)
{
    // first append Y at the end of X
    string XY = X.append(Y);
  
    // then append X at the end of Y
    string YX = Y.append(X);
  
    // Now see which of the two formed numbers is greater
    return XY.compare(YX) > 0 ? 1 : 0;
}
  
// Function to print the largest value
// from the vector of strings
void printLargest(vector<string> arr)
{
    // Sort the numbers using comparison function 
    // myCompare() to compare two strings.
    // Refer http:// www.cplusplus.com/reference/algorithm/sort/
    sort(arr.begin(), arr.end(), myCompare);
  
    for (int i = 0; i < arr.size(); i++)
        cout << arr[i];
  
    cout << "\n";
}
  
// Function to return the maximum number
// possible from nodes at each level
// using level order traversal
int maxLevelNumber(struct Node* root)
{
    // Base case
    if (root == NULL)
        return 0;
  
    // Initialize result
    int result = root->data;
  
    // Level Order Traversal
    queue<Node*> q;
    q.push(root);
  
    while (!q.empty()) {
  
        // Get the size of the queue for the level
        int count = q.size();
        vector<string> v;
        // Iterate over all the nodes
        while (count--) {
  
            // Dequeue nodes from queue
            Node* temp = q.front();
            q.pop();
  
            // push that node to vector
            v.push_back(to_string(temp->data));
            // Push left and right nodes to queue
            // if present
            if (temp->left != NULL)
                q.push(temp->left);
            if (temp->right != NULL)
                q.push(temp->right);
        }
  
        // Print the maximum number at that level
        printLargest(v);
    }
  
    return result;
}
  
/* Helper function that allocates a new node with the
given data and NULL left and right pointers. */
struct Node* newNode(int data)
{
    struct Node* node = new Node;
    node->data = data;
    node->left = node->right = NULL;
    return (node);
}
  
// Driver code
int main()
{
    struct Node* root = newNode(1);
    root->left = newNode(2);
    root->right = newNode(3);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right->right = newNode(8);
    root->right->right->left = newNode(6);
    root->right->right->right = newNode(7);
  
   /* Constructed Binary tree is:
            1
           / \
          2   3
         / \   \
        4   5   8
               / \
               6 7              */
    maxLevelNumber(root);
    return 0;
}

chevron_right


Output:

1
32
854
76

Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.


Article Tags :
Practice Tags :


1


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.