Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • DSA
  • Interview Problems on Queue
  • Practice Queue
  • MCQs on Queue
  • Queue Tutorial
  • Operations
  • Applications
  • Implementation
  • Stack vs Queue
  • Types of Queue
  • Circular Queue
  • Deque
  • Priority Queue
  • Stack using Queue
  • Advantages & Disadvantages
Open In App
Next Article:
Find the largest Perfect Subtree in a given Binary Tree
Next article icon

Find Kth largest number in a given Binary Tree

Last Updated : 21 Oct, 2024
Comments
Improve
Suggest changes
Like Article
Like
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 

reverse-tree-path-using-queue

Output: 5
Explanation: The third largest element in the given binary tree is 5.

Input: k = 1

1

Output: 20
Explanation: The first largest element in the given binary tree is 20.

The simple approach to solve this question is to store the nodes of the given binary tree in an array and then sort this array. return the kth largest number from this sorted array.

Approach:

The above approach can be made efficient by ball 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. Then return the Kth largest element in the priority queue. 

Below is the implementation of the above approach:

C++
// C++ program to find kth largest // number in a binary tree. #include <bits/stdc++.h> using namespace std;  class Node { public:     int data;     Node* left, *right;     Node (int x) {         data = x;         left = nullptr;         right = nullptr;     } };  // Function to store node values into // priority queue. void storeNodes(Node* root, priority_queue<int, vector<int>,                  greater<int>> &pq, int k) {     if (root == nullptr) return;          // If size of pq is less than k, or the top      // element of pq is less than root node.     if (pq.size() < k || root->data > pq.top()) {         if (pq.size() == k) pq.pop();         pq.push(root->data);     }              storeNodes(root->left, pq, k);     storeNodes(root->right, pq, k); }  // Function to find kth largest number int kthLargest(Node* root, int k) {          // store the values into priority_queue.     priority_queue<int, vector<int>, greater<int>> pq;     storeNodes(root, pq, k);          // If size of tree is less than k.     if (k>pq.size()) {         return -1;     }          return pq.top(); }  int main() {          // Construct the following binary tree     //             5     //           /   \     //         1      2     //       /  \    /     //      0    4  3        Node *root = new Node(5);     root->left = new Node(1);     root->right = new Node(2);     root->left->left = new Node(0);     root->left->right = new Node(4);     root->right->left = new Node(3);      int k = 3;     cout << kthLargest(root, k) << endl;      return 0; } 
Java
// Java program to find kth largest // number in a binary tree. import java.util.ArrayList; import java.util.PriorityQueue;  class Node {     int data;     Node left, right;      Node(int x) {         data = x;         left = null;         right = null;     } }  class GfG {          // Function to store node values into     // priority queue.     static void storeNodes(Node root, 					PriorityQueue<Integer> pq, int k) {         if (root == null) return;                  // If size of pq is less than k, or the top          // element of pq is less than root node.         if (pq.size() < k || root.data > pq.peek()) {             if (pq.size() == k) pq.poll();             pq.offer(root.data);         }                  storeNodes(root.left, pq, k);         storeNodes(root.right, pq, k);     }      // Function to find kth largest number     static int kthLargest(Node root, int k) {                  // store the values into        	// priority_queue.         PriorityQueue<Integer> pq = new PriorityQueue<>();         storeNodes(root, pq, k);                  // If size of tree is less than k.         if (k > pq.size()) {             return -1;         }                  return pq.peek();     }      public static void main(String[] args) {                  // Construct the following binary tree         //             5         //           /   \         //         1      2         //       /  \    /         //      0    4  3            Node root = new Node(5);         root.left = new Node(1);         root.right = new Node(2);         root.left.left = new Node(0);         root.left.right = new Node(4);         root.right.left = new Node(3);          int k = 3;         System.out.println(kthLargest(root, k));     } } 
Python
# Python program to find kth largest # number in a binary tree. import heapq  class Node:     def __init__(self, x):         self.data = x         self.left = None         self.right = None  # Function to store node values into # priority queue. def storeNodes(root, pq, k):     if root is None:         return          # If size of pq is less than k, or the top      # element of pq is less than root node.     if len(pq) < k or root.data > pq[0]:         if len(pq) == k:             heapq.heappop(pq)         heapq.heappush(pq, root.data)          storeNodes(root.left, pq, k)     storeNodes(root.right, pq, k)  # Function to find kth largest number def kthLargest(root, k):          # store the values into priority_queue.     pq = []     storeNodes(root, pq, k)          # If size of tree is less than k.     if k > len(pq):         return -1          return pq[0]  if __name__ == "__main__":          # Construct the following binary tree     #             5     #           /   \     #         1      2     #       /  \    /     #      0    4  3        root = Node(5)     root.left = Node(1)     root.right = Node(2)     root.left.left = Node(0)     root.left.right = Node(4)     root.right.left = Node(3)      k = 3     print(kthLargest(root, k)) 
C#
// C# program to find kth largest // number in a binary tree. using System; using System.Collections.Generic;  class Node {     public int Data;     public Node Left, Right;      public Node(int x) {         Data = x;         Left = null;         Right = null;     } }  class GfG {      // Function to store node values into a list.     static void StoreNodes(Node root, List<int> values, int k) {         if (root == null) return;          values.Add(root.Data);         StoreNodes(root.Left, values, k);         StoreNodes(root.Right, values, k);     }      // Function to find the kth largest number     static int KthLargest(Node root, int k) {         List<int> values = new List<int>();         StoreNodes(root, values, k);          // Sort the list in descending order         values.Sort((a, b) => b.CompareTo(a));          // If size of tree is less than k.         if (k > values.Count) {             return -1;         }          return values[k - 1];     }      static void Main(string[] args) {                // Construct the following binary tree         //             5         //           /   \         //         1      2         //       /  \    /         //      0    4  3            Node root = new Node(5);         root.Left = new Node(1);         root.Right = new Node(2);         root.Left.Left = new Node(0);         root.Left.Right = new Node(4);         root.Right.Left = new Node(3);          int k = 3;         Console.WriteLine(KthLargest(root, k));     } } 
JavaScript
// JavaScript program to find kth largest // number in a binary tree. class Node {     constructor(x) {         this.data = x;         this.left = null;         this.right = null;     } }  // Function to store node values into // priority queue. function storeNodes(root, pq, k) {     if (root === null) return;          // If size of pq is less than k, or the top      // element of pq is less than root node.     if (pq.length < k || root.data > pq[0]) {         if (pq.length === k) pq.shift();         pq.push(root.data);         pq.sort((a, b) => a - b);     }          storeNodes(root.left, pq, k);     storeNodes(root.right, pq, k); }  // Function to find kth largest number function kthLargest(root, k) {          // store the values into priority_queue.     const pq = [];     storeNodes(root, pq, k);          // If size of tree is less than k.     if (k > pq.length) {         return -1;     }          return pq[0];  }      // Construct the following binary tree //             5 //           /   \ //         1      2 //       /  \    / //      0    4  3    const root = new Node(5); root.left = new Node(1); root.right = new Node(2); root.left.left = new Node(0); root.left.right = new Node(4); root.right.left = new Node(3);  const k = 3; console.log(kthLargest(root, k)); 

Output
3 

Time Complexity: O(nlogk), Inserting an element into a priority queue takes O(log k) time. Thus, for n nodes, the overall time complexity becomes O(n log k).
Auxiliary Space: O(max(h,k)) , where h is the height of the binary tree.



Next Article
Find the largest Perfect Subtree in a given Binary Tree

N

namanaggarwal1
Improve
Article Tags :
  • DSA
  • Heap
  • Mathematical
  • Sorting
  • Tree
  • priority-queue
Practice Tags :
  • Heap
  • Mathematical
  • priority-queue
  • Sorting
  • Tree

Similar Reads

  • Find the largest Perfect Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size of largest Perfect sub-tree in the given Binary Tree. Perfect Binary Tree - A Binary tree is Perfect Binary Tree in which all internal nodes have two children and all leaves are at the same level. Examples: Input: 1 / \ 2 3 / \ / 4 5 6 Output: Size :
    12 min read
  • Find the largest Complete Subtree in a given Binary Tree
    Given a Binary Tree, the task is to find the size and also the inorder traversal of the largest Complete sub-tree in the given Binary Tree. Complete Binary Tree - A Binary tree is a Complete Binary Tree if all levels are filled except possibly the last level and the last level has all keys as left a
    13 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 b
    9 min read
  • Find K smallest leaf nodes from a given Binary Tree
    Given a binary tree and an integer K, the task is to find the K smallest leaf nodes from the given binary tree. The number of leaf nodes will always be at least K. Examples: Input: 1 / \ 2 3 / \ / \ 4 5 6 7 / \ \ 21 8 19Output: 6 8 19Explanation:There are 4 leaf nodes in the above binary tree out of
    7 min read
  • Largest BST in a Binary Tree
    Given a Binary Tree, the task is to return the size of the largest subtree which is also a Binary Search Tree (BST). If the complete Binary Tree is BST, then return the size of the whole tree. Examples: Input: Output: 3 Explanation: The below subtree is the maximum size BST: Input: Output: 3 Explana
    14 min read
  • Largest element in an N-ary Tree
    Given an n-ary tree containing positive node values, the task is to find the node with the largest value in the given n-ary tree.Note: An n-ary tree is a tree where each node can have zero or more children nodes. Unlike a binary tree, which has at most two children per node (left and right), the n-a
    5 min read
  • Find the maximum node at a given level in a binary tree
    Given a Binary Tree and a Level. The task is to find the node with the maximum value at that given level. The idea is to traverse the tree along depth recursively and return the nodes once the required level is reached and then return the maximum of left and right subtrees for each subsequent call.
    13 min read
  • Find largest subtree sum in a tree
    Given a Binary Tree, the task is to find a subtree with the maximum sum in the tree. Examples: Input: Output: 28Explanation: As all the tree elements are positive, the largest subtree sum is equal to sum of all tree elements. Input: Output: 7Explanation: Subtree with largest sum is: Table of Content
    15+ min read
  • Find the maximum sum leaf to root path in a Binary Tree
    Given a Binary Tree, the task is to find the maximum sum path from a leaf to a root. Example : Input: Output: 60Explanantion: There are three leaf to root paths 20->30->10, 5->30->10 and 15->10. The sums of these three paths are 60, 45 and 25 respectively. The maximum of them is 60 an
    15+ min read
  • Length of longest straight path from a given Binary Tree
    Given a Binary Tree, the task is to find the length of the longest straight path of the given binary tree. Straight Path is defined as the path that starts from any node and ends at another node in the tree such that the direction of traversal from the source node to the destination node always rema
    8 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences