Open In App

Find Kth largest number in a given Binary Tree

Last Updated : 24 Aug, 2021
Improve
Improve
Like Article
Like
Save
Share
Report

Given a Binary Tree consisting of N nodes and a positive integer K, the task is to find the Kth largest number in the given tree.
Examples:

Input: K = 3 
              1
           /    \
        2        3
     /  \       /  \ 
  4     5    6    7
Output: 5
Explanation: The third largest element in the given binary tree is 5.

Input: K = 1
              1
           /    \
        2        3
Output: 1
Explanation: The first largest element in the given binary tree is 1.

Naive Approach: Flatten the given binary tree and then sort the array. Print the Kth largest number from this sorted array now.
 

Efficient Approach: The above approach can be made efficient by storing all the elements of the Tree in a priority queue, as the elements are stored based on the priority order, which is ascending by default. Though the complexity will remain the same as the above approach, here we can avoid the additional sorting step. 
Just print the Kth largest element in the priority queue

 

Below is the implementation of the above approach:

 

C++




// C++ program for the above approach
#include <bits/stdc++.h>
using namespace std;
 
// Struct binary tree node
struct Node {
    int data;
    Node *left, *right;
};
 
// Function to create a new node of
// the tree
Node* newNode(int data)
{
    Node* temp = new Node();
    temp->data = data;
    temp->left = temp->right = NULL;
    return temp;
}
 
// Utility function to find the Kth
// largest element in the given tree
int findKthLargest(priority_queue<int,
                                  vector<int> >& pq,
                   int k)
{
    // Loop until priority queue is not
    // empty and K greater than 0
    while (--k && !pq.empty()) {
        pq.pop();
    }
 
    // If PQ is not empty then return
    // the top element
    if (!pq.empty()) {
        return pq.top();
    }
 
    // Otherwise, return -1
    return -1;
}
 
// Function to traverse the given
// binary tree
void traverse(
    Node* root, priority_queue<int,
                               vector<int> >& pq)
{
 
    if (!root) {
        return;
    }
 
    // Pushing values in binary tree
    pq.push(root->data);
 
    // Left and Right Recursive Call
    traverse(root->left, pq);
    traverse(root->right, pq);
}
 
// Function to find the Kth largest
// element in the given tree
void findKthLargestTree(Node* root, int K)
{
 
    // Stores all elements tree in PQ
    priority_queue<int, vector<int> > pq;
 
    // Function Call
    traverse(root, pq);
 
    // Function Call
    cout << findKthLargest(pq, K);
}
 
// Driver Code
int main()
{
    // Given Input
    Node* root = newNode(1);
    root->left = newNode(2);
    root->left->left = newNode(4);
    root->left->right = newNode(5);
    root->right = newNode(3);
    root->right->right = newNode(7);
    root->right->left = newNode(6);
    int K = 3;
 
    findKthLargestTree(root, K);
 
    return 0;
}


Java




// Java program for the above approach
import java.util.*;
public class Main
{
   
    // Struct binary tree node
    static class Node
    {
        int data;
        Node left;
        Node right;
    }
     
    // Function to create new node of the tree
    static Node newNode(int data)
    {
        Node temp = new Node();
        temp.data = data;
        temp.left = null;
        temp.right = null;
        return temp;
    }
     
    // Stores all elements tree in PQ
    static Vector<Integer> pq = new Vector<Integer>();
      
    // Utility function to find the Kth
    // largest element in the given tree
    static int findKthLargest(int k)
    {
        // Loop until priority queue is not
        // empty and K greater than 0
        --k;
        while (k > 0 && pq.size() > 0) {
            pq.remove(0);
            --k;
        }
        
        // If PQ is not empty then return
        // the top element
        if (pq.size() > 0) {
            return pq.get(0);
        }
        
        // Otherwise, return -1
        return -1;
    }
        
    // Function to traverse the given
    // binary tree
    static void traverse(Node root)
    {
        
        if (root == null) {
            return;
        }
        
        // Pushing values in binary tree
        pq.add(root.data);
        Collections.sort(pq);
        Collections.reverse(pq);
        
        // Left and Right Recursive Call
        traverse(root.left);
        traverse(root.right);
    }
        
    // Function to find the Kth largest
    // element in the given tree
    static void findKthLargestTree(Node root, int K)
    {
        // Function Call
        traverse(root);
        
        // Function Call
        System.out.print(findKthLargest(K));
    }
 
  // Driver code
    public static void main(String[] args)
    {
       
        // Given Input
        Node root = newNode(1);
        root.left = newNode(2);
        root.left.left = newNode(4);
        root.left.right = newNode(5);
        root.right = newNode(3);
        root.right.right = newNode(7);
        root.right.left = newNode(6);
        int K = 3;
        
        findKthLargestTree(root, K);
    }
}
 
// This code is contributed by divyesh07.


Python3




# Python3 program for the above approach
class Node:
    # Struct binary tree node
    def __init__(self, data):
        self.data = data
        self.left = None
        self.right = None
 
# Stores all elements tree in PQ
pq = []
   
# Utility function to find the Kth
# largest element in the given tree
def findKthLargest(k):
    # Loop until priority queue is not
    # empty and K greater than 0
    k-=1
    while (k > 0 and len(pq) > 0):
        pq.pop(0)
        k-=1
     
    # If PQ is not empty then return
    # the top element
    if len(pq) > 0:
        return pq[0]
     
    # Otherwise, return -1
    return -1
     
# Function to traverse the given
# binary tree
def traverse(root):
    if (root == None):
        return
     
    # Pushing values in binary tree
    pq.append(root.data)
    pq.sort()
    pq.reverse()
     
    # Left and Right Recursive Call
    traverse(root.left)
    traverse(root.right)
     
# Function to find the Kth largest
# element in the given tree
def findKthLargestTree(root, K):
    # Function Call
    traverse(root);
     
    # Function Call
    print(findKthLargest(K))
 
# Given Input
root = Node(1)
root.left = Node(2)
root.left.left = Node(4)
root.left.right = Node(5)
root.right = Node(3)
root.right.right = Node(7)
root.right.left = Node(6)
K = 3
 
findKthLargestTree(root, K)
 
# This code is contributed by mukesh07.


C#




// C# program for the above approach
using System;
using System.Collections.Generic;
class GFG {
     
    // Struct binary tree node
    class Node
    {
        public int data;
        public Node left, right;
    };
     
    // Function to create a new node of the tree
    static Node newNode(int data)
    {
      Node temp = new Node();
      temp.data = data;
      temp.left = null;
      temp.right = null;
      return temp;
    }
     
    // Stores all elements tree in PQ
    static List<int> pq = new List<int>();
     
    // Utility function to find the Kth
    // largest element in the given tree
    static int findKthLargest(int k)
    {
        // Loop until priority queue is not
        // empty and K greater than 0
        --k;
        while (k > 0 && pq.Count > 0) {
            pq.RemoveAt(0);
            --k;
        }
       
        // If PQ is not empty then return
        // the top element
        if (pq.Count > 0) {
            return pq[0];
        }
       
        // Otherwise, return -1
        return -1;
    }
       
    // Function to traverse the given
    // binary tree
    static void traverse(Node root)
    {
       
        if (root == null) {
            return;
        }
       
        // Pushing values in binary tree
        pq.Add(root.data);
        pq.Sort();
        pq.Reverse();
       
        // Left and Right Recursive Call
        traverse(root.left);
        traverse(root.right);
    }
       
    // Function to find the Kth largest
    // element in the given tree
    static void findKthLargestTree(Node root, int K)
    {
        // Function Call
        traverse(root);
       
        // Function Call
        Console.Write(findKthLargest(K));
    }
 
  static void Main() {
    // Given Input
    Node root = newNode(1);
    root.left = newNode(2);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right = newNode(3);
    root.right.right = newNode(7);
    root.right.left = newNode(6);
    int K = 3;
   
    findKthLargestTree(root, K);
  }
}
 
// This code is contributed by divyeshrabadiya07.


Javascript




<script>
    // Javascript program for the above approach
     
    // Struct binary tree node
    class Node
    {
        constructor(data) {
           this.left = null;
           this.right = null;
           this.data = data;
        }
    }
      
      // Function to create a new node of the tree
    function newNode(data)
    {
        let temp = new Node(data);
        return temp;
    }
     
    // Stores all elements tree in PQ
    let pq = [];
      
    // Utility function to find the Kth
    // largest element in the given tree
    function findKthLargest(k)
    {
        // Loop until priority queue is not
        // empty and K greater than 0
        --k;
        while (k > 0 && pq.length > 0) {
            pq.shift();
            --k;
        }
        
        // If PQ is not empty then return
        // the top element
        if (pq.length > 0) {
            return pq[0];
        }
        
        // Otherwise, return -1
        return -1;
    }
        
    // Function to traverse the given
    // binary tree
    function traverse(root)
    {
        
        if (root == null) {
            return;
        }
        
        // Pushing values in binary tree
        pq.push(root.data);
        pq.sort(function(a, b){return a - b});
        pq.reverse();
        
        // Left and Right Recursive Call
        traverse(root.left);
        traverse(root.right);
    }
        
    // Function to find the Kth largest
    // element in the given tree
    function findKthLargestTree(root, K)
    {
        // Function Call
        traverse(root);
        
        // Function Call
        document.write(findKthLargest(K));
    }
     
    // Given Input
    let root = newNode(1);
    root.left = newNode(2);
    root.left.left = newNode(4);
    root.left.right = newNode(5);
    root.right = newNode(3);
    root.right.right = newNode(7);
    root.right.left = newNode(6);
    let K = 3;
    
    findKthLargestTree(root, K);
     
    // This code is contributed by decode2207.
</script>


 
 

Output: 

5

 

 

Time Complexity: O((N + K)log N)
Auxiliary Space: O(N)

 



Similar Reads

Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
In this article, we will discuss the complexity of different operations in binary trees including BST and AVL trees. Before understanding this article, you should have a basic idea about Binary Tree, Binary Search Tree, and AVL Tree. The main operations in a binary tree are: search, insert and delete. We will see the worst-case time complexity of t
4 min read
Convert a Binary Tree into its Mirror Tree (Invert Binary Tree)
Given a binary tree, the task is to convert the binary tree into its Mirror tree. Mirror of a Binary Tree T is another Binary Tree M(T) with left and right children of all non-leaf nodes interchanged. [caption width="800"]Mirror Tree[/caption]Recommended PracticeMirror TreeTry It!The idea is to traverse recursively and swap the right and left subtr
17 min read
Given an array and two integers l and r, find the kth largest element in the range [l, r]
Given an unsorted array arr[] of n integers and an integer k, the task is to find the kth largest element in the given index range [l, r]Examples: Input: arr[] = {5, 3, 2, 4, 1}, k = 4, l = 1, r = 5 Output: 4 4 will be the 4th element when arr[0...4] is sorted.Input: arr[] = {1, 4, 2, 3, 5, 7, 6}, k = 3, l = 3, r = 6 Output: 5 Approach: A naive sol
11 min read
Find the Kth Largest Tribonacci Number Node in a Singly Linked List
Given a singly linked list containing integers, the task is to find the Kth largest Tribonacci number in the linked list. Note: A Tribonacci number is a series of numbers where each number is the sum of the three preceding numbers. The Tribonacci Sequence: 0, 0, 1, 1, 2, 4, 7, 13, 24, 44, 81, 149, 274, 504, 927, 1705, 3136, 5768....... Examples: In
10 min read
Find the kth node in vertical order traversal of a Binary Tree
Given a binary tree and an integer k, the task is to print the kth node in the vertical order traversal of binary tree.If no such node exists then print -1.The vertical order traversal of a binary tree means to print it vertically.Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 \ \ 8 9 k = 3 Output: 1 The vertical order traversal of above tree is: 4 2 1
9 min read
Find the numbers present at Kth level of a Fibonacci Binary Tree
Given a number K, the task is to print the fibonacci numbers present at Kth level of a Fibonacci Binary Tree.Examples: Input: K = 3 Output: 2, 3, 5, 8 Explanation: Fibonacci Binary Tree for 3 levels: 0 / \ 1 1 /\ / \ 2 3 5 8 Numbers present at level 3: 2, 3, 5, 8 Input: K = 2 Output: 1, 1 Explanation: Fibonacci Binary Tree for 2 levels: 0 / \ 1 1 N
12 min read
Path from a given source to a given destination having Kth largest weight in a Graph
Given a weighted graph consisting of N nodes and M edges, a source vertex, a destination vertex, and an integer K, the task is to find the path with Kth largest weight from source to destination in the graph. Examples: Input: N = 7, M = 8, source = 0, destination = 6, K = 3, Edges[][] = {{0, 1, 10}, {1, 2, 10}, {2, 3, 10}, {0, 3, 40}, {3, 4, 2}, {4
14 min read
Kth largest odd number in a given range
Given two variables L and R, indicating a range of integers from L to R inclusive, and a number K, the task is to find Kth largest odd number. If K &gt; number of odd numbers in the range L to R then return 0. Examples: Input: L = -10, R = 10, K = 8Output: -5Explanation: The odd Numbers in the range are -9, -7, -5, -3, -1, 1, 3, 5, 7, 9 and the 8th
7 min read
Finding Kth largest number in given array of large numbers
Given an array arr[] of strings representing large numbers and an integer K, the task is to find Kth largest integer in given array. Examples: Input: arr[] = { "10", "7", "3", "6" }, K = 3Output: "6"Explanation : Arranging the array in non-decreasing manner will give { "3", "6", "7", "10" }.Clearly 3rd largest integer is 6. Input: arr[] = { "10", "
5 min read
Kth largest element in an N-array Tree
Given an N-array Tree consisting of N nodes and an integer K, the task is to find the Kth largest element in the given N-ary Tree. Examples: Input: K = 3 Output: 77 Explanation:The 3rd largest element in the given N-array tree is 77. Input: K = 4 Output: 3 Approach: The given problem can be solved by finding the largest element in the given range f
9 min read