Find Kth largest number in a given Binary Tree

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 nodestruct Node {Â Â Â Â int data;Â Â Â Â Node *left, *right;};Â
// Function to create a new node of// the treeNode* 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 treeint 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 treevoid 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 treevoid 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 Codeint 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 approachimport 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 approachclass Node:    # Struct binary tree node    def __init__(self, data):        self.data = data        self.left = None        self.right = NoneÂ
# Stores all elements tree in PQpq = []   # Utility function to find the Kth# largest element in the given treedef 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 treedef 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 treedef findKthLargestTree(root, K):    # Function Call    traverse(root);         # Function Call    print(findKthLargest(K))Â
# Given Inputroot = 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 approachusing 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> |
Â
Â
5
Â
Â
Time Complexity: O((N + K)log N)
Auxiliary Space: O(N)
Â
Ready to dive in? Explore our Free Demo Content and join our DSA course, trusted by over 100,000 zambiatek!



