Maximum number of leaf nodes that can be visited within the given budget
Given a binary tree and an integer b representing budget. The task is to find the count of maximum number of leaf nodes that can be visited under the given budget if cost of visiting a leaf node is equal to level of that leaf node.
Note: Root of the tree is at level 1.
Examples:
Input: b = 8
10
/ \
8 15
/ / \
3 11 18
\
13
Output: 2
For the above binary tree, leaf nodes are 3,
13 and 18 at levels 3, 4 and 3 respectively.
Cost for visiting leaf node 3 is 3
Cost for visiting leaf node 13 is 4
Cost for visiting leaf node 18 is 3
Thus with given budget = 8, we can at maximum
visit two leaf nodes.
Input: b = 1
8
/ \
7 10
/
3
Output: 0
For the above binary tree, leaf nodes are
3 and 10 at levels 3 and 2 respectively.
Cost for visiting leaf node 3 is 3
Cost for visiting leaf node 10 is 2
In given budget = 1, we can't visit
any leaf node.
Approach:
- Traverse the binary tree using level order traversal, and store the level of all the leaf nodes in a priority queue.
- Remove an element from the priority queue one by one, check if this value is within the budget.
- If Yes then subtract this value from the budget and update count = count + 1.
- Else, print the count of maximum leaf nodes that can be visited within the given budget.
Below is the implementation of the above approach:
C++
#include <bits/stdc++.h>
using namespace std;
struct Node {
Node* left;
Node* right;
int data;
Node( int key)
{
data = key;
this ->left = nullptr;
this ->right = nullptr;
}
};
Node* newNode( int key)
{
Node* temp = new Node(key);
return temp;
}
vector< int > pq;
void levelOrder(Node* root)
{
vector<Node*> q;
int len, level = 0;
Node* temp;
if (root == nullptr)
return ;
q.push_back(root);
while ( true ) {
len = q.size();
if (len == 0)
break ;
level++;
while (len > 0) {
temp = q[0];
q.erase(q.begin());
if (temp->left != nullptr)
q.push_back(temp->left);
if (temp->right != nullptr)
q.push_back(temp->right);
if (temp->left == nullptr && temp->right == nullptr)
{
pq.push_back(level);
sort(pq.begin(), pq.end());
reverse(pq.begin(), pq.end());
}
len--;
}
}
}
int countLeafNodes(Node* root, int budget)
{
levelOrder(root);
int val;
int count = 0;
while (pq.size() != 0) {
val = pq[0];
pq.erase(pq.begin());
if (val <= budget) {
count++;
budget -= val;
}
else
break ;
}
return count;
}
int main()
{
Node* root = newNode(10);
root->left = newNode(8);
root->right = newNode(15);
root->left->left = newNode(3);
root->left->left->right = newNode(13);
root->right->left = newNode(11);
root->right->right = newNode(18);
int budget = 8;
cout << countLeafNodes(root, budget);
return 0;
}
|
Java
import java.io.*;
import java.util.*;
import java.lang.*;
class Node {
int data;
Node left, right;
Node( int key)
{
data = key;
left = right = null ;
}
}
class GFG {
static PriorityQueue<Integer> pq;
static void levelOrder(Node root)
{
Queue<Node> q = new LinkedList<>();
int len, level = 0 ;
Node temp;
if (root == null )
return ;
q.add(root);
while ( true ) {
len = q.size();
if (len == 0 )
break ;
level++;
while (len > 0 ) {
temp = q.remove();
if (temp.left != null )
q.add(temp.left);
if (temp.right != null )
q.add(temp.right);
if (temp.left == null && temp.right == null )
pq.add(level);
len--;
}
}
}
static int countLeafNodes(Node root, int budget)
{
pq = new PriorityQueue<>();
levelOrder(root);
int val;
int count = 0 ;
while (pq.size() != 0 ) {
val = pq.poll();
if (val <= budget) {
count++;
budget -= val;
}
else
break ;
}
return count;
}
public static void main(String args[])
{
Node root = new Node( 10 );
root.left = new Node( 8 );
root.right = new Node( 15 );
root.left.left = new Node( 3 );
root.left.left.right = new Node( 13 );
root.right.left = new Node( 11 );
root.right.right = new Node( 18 );
int budget = 8 ;
System.out.println(countLeafNodes(root, budget));
}
}
|
Python3
class Node:
def __init__( self , key):
self .data = key
self .left = None
self .right = None
pq = []
def levelOrder(root):
q = []
level = 0
if (root = = None ):
return
q.append(root)
while ( True ) :
Len = len (q)
if ( Len = = 0 ):
break
level + = 1
while ( Len > 0 ) :
temp = q[ 0 ]
del q[ 0 ]
if (temp.left ! = None ):
q.append(temp.left)
if (temp.right ! = None ):
q.append(temp.right)
if (temp.left = = None and temp.right = = None ):
pq.append(level)
pq.sort()
pq.reverse()
Len - = 1
return pq
def countLeafNodes(root, budget):
pq = levelOrder(root)
count = 0
while ( len (pq) ! = 0 ) :
val = pq[ 0 ]
del pq[ 0 ]
if (val < = budget) :
count + = 1
budget - = val
else :
break
return count
root = Node( 10 )
root.left = Node( 8 )
root.right = Node( 15 );
root.left.left = Node( 3 )
root.left.left.right = Node( 13 )
root.right.left = Node( 11 )
root.right.right = Node( 18 )
budget = 8
print (countLeafNodes(root, budget))
|
C#
using System;
using System.Collections.Generic;
class GFG {
class Node
{
public Node left, right;
public int data;
};
static Node newNode( int key)
{
Node temp = new Node();
temp.data = key;
temp.left = temp.right = null ;
return temp;
}
static List< int > pq;
static void levelOrder(Node root)
{
List<Node> q = new List<Node>();
int len, level = 0;
Node temp;
if (root == null )
return ;
q.Add(root);
while ( true ) {
len = q.Count;
if (len == 0)
break ;
level++;
while (len > 0) {
temp = q[0];
q.RemoveAt(0);
if (temp.left != null )
q.Add(temp.left);
if (temp.right != null )
q.Add(temp.right);
if (temp.left == null && temp.right == null )
{
pq.Add(level);
pq.Sort();
pq.Reverse();
}
len--;
}
}
}
static int countLeafNodes(Node root, int budget)
{
pq = new List< int >();
levelOrder(root);
int val;
int count = 0;
while (pq.Count != 0) {
val = pq[0];
pq.RemoveAt(0);
if (val <= budget) {
count++;
budget -= val;
}
else
break ;
}
return count;
}
static void Main() {
Node root = newNode(10);
root.left = newNode(8);
root.right = newNode(15);
root.left.left = newNode(3);
root.left.left.right = newNode(13);
root.right.left = newNode(11);
root.right.right = newNode(18);
int budget = 8;
Console.Write(countLeafNodes(root, budget));
}
}
|
Javascript
<script>
class Node {
constructor(data) {
this .left = null ;
this .right = null ;
this .data = data;
}
}
let pq = [];
function levelOrder(root)
{
let q = [];
let len, level = 0;
let temp;
if (root == null )
return ;
q.push(root);
while ( true ) {
len = q.length;
if (len == 0)
break ;
level++;
while (len > 0) {
temp = q.shift();
if (temp.left != null )
q.push(temp.left);
if (temp.right != null )
q.push(temp.right);
if (temp.left == null && temp.right == null )
{
pq.push(level);
pq.sort( function (a, b){ return a - b});
pq.reverse();
}
len--;
}
}
}
function countLeafNodes(root, budget)
{
pq = [];
levelOrder(root);
let val;
let count = 0;
while (pq.length != 0) {
val = pq[0];
pq.shift();
if (val <= budget) {
count++;
budget -= val;
}
else
break ;
}
return count;
}
let root = new Node(10);
root.left = new Node(8);
root.right = new Node(15);
root.left.left = new Node(3);
root.left.left.right = new Node(13);
root.right.left = new Node(11);
root.right.right = new Node(18);
let budget = 8;
document.write(countLeafNodes(root, budget));
</script>
|
Last Updated :
18 Aug, 2021
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...