The Wayback Machine - https://web.archive.org/web/20241008180334/https://www.geeksforgeeks.org/kth-largest-element-bst-using-constant-extra-space/
Open In App

K’th Largest element in BST using constant extra space

Last Updated : 12 Aug, 2022
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

Given a binary search tree, task is to find Kth largest element in the binary search tree.

Example: 

Input :  k = 3
         Root of following BST
            10
          /    \
         4      20
        /      /   \
       2     15     40
Output : 15

The idea is to use Reverse Morris Traversal which is based on Threaded Binary Trees. Threaded binary trees use the NULL pointers to store the successor and predecessor information which helps us to utilize the wasted memory by those NULL pointers.

The special thing about Morris traversal is that we can do Inorder traversal without using stack or recursion which saves us memory consumed by stack or recursion call stack.

Reverse Morris traversal is just the reverse of Morris traversal which is majorly used to do Reverse Inorder traversal with constant O(1) extra memory consumed as it does not uses any Stack or Recursion.

To find Kth largest element in a Binary search tree, the simplest logic is to do reverse inorder traversal and while doing reverse inorder traversal simply keep a count of number of Nodes visited. When the count becomes equal to k, we stop the traversal and print the data. It uses the fact that reverse inorder traversal will give us a list sorted in descending order. 

Algorithm

1) Initialize Current as root.
2) Initialize a count variable to 0.
3) While current is not NULL :
   3.1) If current has no right child
   a) Increment count and check if count is equal to K.
      1) If count is equal to K, simply return current 
         Node as it is the Kth largest Node.
   b) Otherwise, Move to the left child of current.

   3.2) Else, here we have 2 cases:
   a) Find the inorder successor of current Node. 
      Inorder successor is the left most Node 
      in the right subtree or right child itself.
   b) If the left child of the inorder successor is NULL:
      1) Set current as the left child of its inorder 
         successor.
      2) Move current Node to its right.
   c) Else, if the threaded link between the current Node 
      and it's inorder successor already exists :
      1) Set left pointer of the inorder successor as NULL.
      2) Increment count and check if count is equal to K.
           a) If count is equal to K, simply return current
              Node as it is the Kth largest Node.

      3) Otherwise, Move current to it's left child.

Implementation:

C++




// CPP code for finding K-th largest Node using O(1)
// extra memory and reverse Morris traversal.
#include <bits/stdc++.h>
using namespace std;
 
struct Node {
    int data;
    struct Node *left, *right;
};
 
// helper function to create a new Node
Node* newNode(int data)
{
    Node* temp = new Node;
    temp->data = data;
    temp->right = temp->left = NULL;
    return temp;
}
 
Node* KthLargestUsingMorrisTraversal(Node* root, int k)
{
    Node* curr = root;
    Node* Klargest = NULL;
 
    // count variable to keep count of visited Nodes
    int count = 0;
 
    while (curr != NULL) {
        // if right child is NULL
        if (curr->right == NULL) {
 
            // first increment count and check if count = k
            if (++count == k)
                Klargest = curr;
 
            // otherwise move to the left child
            curr = curr->left;
        }
 
        else {
 
            // find inorder successor of current Node
            Node* succ = curr->right;
 
            while (succ->left != NULL && succ->left != curr)
                succ = succ->left;
 
            if (succ->left == NULL) {
 
                // set left child of successor to the
                // current Node
                succ->left = curr;
 
                // move current to its right
                curr = curr->right;
            }
 
            // restoring the tree back to original binary
            //  search tree removing threaded links
            else {
 
                succ->left = NULL;
 
                if (++count == k)
                    Klargest = curr;
 
                // move current to its left child
                curr = curr->left;
            }
        }
    }
 
    return Klargest;
}
 
int main()
{
    // Your C++ Code
    /* Constructed binary tree is
          4
        /   \
       2     7
     /  \   /  \
    1    3  6    10 */
 
    Node* root = newNode(4);
    root->left = newNode(2);
    root->right = newNode(7);
    root->left->left = newNode(1);
    root->left->right = newNode(3);
    root->right->left = newNode(6);
    root->right->right = newNode(10);
 
    cout << "Finding K-th largest Node in BST : "
         << KthLargestUsingMorrisTraversal(root, 2)->data;
 
    return 0;
}


Java




// Java Program for finding K-th largest Node using O(1)
// extra memory and reverse Morris traversal.
class GfG
{
 
static class Node
{
    int data;
    Node left, right;
}
 
// helper function to create a new Node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.right = null;
    temp.left = null;
    return temp;
}
 
static Node KthLargestUsingMorrisTraversal(Node root, int k)
{
    Node curr = root;
    Node Klargest = null;
 
    // count variable to keep count of visited Nodes
    int count = 0;
 
    while (curr != null)
    {
        // if right child is NULL
        if (curr.right == null)
        {
 
            // first increment count and check if count = k
            if (++count == k)
                Klargest = curr;
 
            // otherwise move to the left child
            curr = curr.left;
        }
 
        else
        {
 
            // find inorder successor of current Node
            Node succ = curr.right;
 
            while (succ.left != null && succ.left != curr)
                succ = succ.left;
 
            if (succ.left == null)
            {
 
                // set left child of successor to the
                // current Node
                succ.left = curr;
 
                // move current to its right
                curr = curr.right;
            }
 
            // restoring the tree back to original binary
            // search tree removing threaded links
            else
            {
 
                succ.left = null;
 
                if (++count == k)
                    Klargest = curr;
 
                // move current to its left child
                curr = curr.left;
            }
        }
    }
    return Klargest;
}
 
// Driver code
public static void main(String[] args)
{
    // Your Java Code
    /* Constructed binary tree is
        4
        / \
    2 7
    / \ / \
    1 3 6 10 */
 
    Node root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(7);
    root.left.left = newNode(1);
    root.left.right = newNode(3);
    root.right.left = newNode(6);
    root.right.right = newNode(10);
 
    System.out.println("Finding K-th largest Node in BST : " +
                    KthLargestUsingMorrisTraversal(root, 2).data);
}
}


Python3




# Python3 code for finding K-th largest
# Node using O(1) extra memory and
# reverse Morris traversal.
 
# helper function to create a new Node
class newNode:
    def __init__(self, data):
        self.data = data
        self.right = self.left = None
 
def KthLargestUsingMorrisTraversal(root, k):
    curr = root
    Klargest = None
 
    # count variable to keep count
    # of visited Nodes
    count = 0
 
    while (curr != None):
         
        # if right child is None
        if (curr.right == None):
 
            # first increment count and
            # check if count = k
            count += 1
            if (count == k):
                Klargest = curr
 
            # otherwise move to the left child
            curr = curr.left
 
        else:
 
            # find inorder successor of
            # current Node
            succ = curr.right
 
            while (succ.left != None and
                   succ.left != curr):
                succ = succ.left
 
            if (succ.left == None):
 
                # set left child of successor
                # to the current Node
                succ.left = curr
 
                # move current to its right
                curr = curr.right
 
            # restoring the tree back to 
            # original binary search tree
            # removing threaded links
            else:
 
                succ.left = None
                count += 1
                if (count == k):
                    Klargest = curr
 
                # move current to its left child
                curr = curr.left
 
    return Klargest
 
# Driver Code
if __name__ == '__main__':
 
    # Constructed binary tree is
    #     4
    #     / \
    # 2     7
    # / \ / \
    # 1 3 6 10
    root = newNode(4)
    root.left = newNode(2)
    root.right = newNode(7)
    root.left.left = newNode(1)
    root.left.right = newNode(3)
    root.right.left = newNode(6)
    root.right.right = newNode(10)
 
    print("Finding K-th largest Node in BST : ",
           KthLargestUsingMorrisTraversal(root, 2).data)
 
# This code is contributed by PranchalK


C#




// C# Program for finding K-th largest Node using O(1)
// extra memory and reverse Morris traversal.
using System;
using System.Collections.Generic;
 
class GfG
{
 
public class Node
{
    public int data;
    public Node left, right;
}
 
// helper function to create a new Node
static Node newNode(int data)
{
    Node temp = new Node();
    temp.data = data;
    temp.right = null;
    temp.left = null;
    return temp;
}
 
static Node KthLargestUsingMorrisTraversal(Node root, int k)
{
    Node curr = root;
    Node Klargest = null;
 
    // count variable to keep count of visited Nodes
    int count = 0;
 
    while (curr != null)
    {
        // if right child is NULL
        if (curr.right == null)
        {
 
            // first increment count and check if count = k
            if (++count == k)
                Klargest = curr;
 
            // otherwise move to the left child
            curr = curr.left;
        }
 
        else
        {
 
            // find inorder successor of current Node
            Node succ = curr.right;
 
            while (succ.left != null && succ.left != curr)
                succ = succ.left;
 
            if (succ.left == null)
            {
 
                // set left child of successor to the
                // current Node
                succ.left = curr;
 
                // move current to its right
                curr = curr.right;
            }
 
            // restoring the tree back to original binary
            // search tree removing threaded links
            else
            {
 
                succ.left = null;
 
                if (++count == k)
                    Klargest = curr;
 
                // move current to its left child
                curr = curr.left;
            }
        }
    }
    return Klargest;
}
 
// Driver code
public static void Main(String[] args)
{
    // Your C# Code
    /* Constructed binary tree is
        4
        / \
    2 7
    / \ / \
    1 3 6 10 */
 
    Node root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(7);
    root.left.left = newNode(1);
    root.left.right = newNode(3);
    root.right.left = newNode(6);
    root.right.right = newNode(10);
 
    Console.Write("Finding K-th largest Node in BST : " +
                    KthLargestUsingMorrisTraversal(root, 2).data);
}
}
 
// This code has been contributed by 29AjayKumar


Javascript




<script>
 
// JavaScript Program for finding
// K-th largest Node using O(1)
// extra memory and reverse
// Morris traversal.
 
 class Node
{
     constructor(){
     this.data = 0;
     this.left = null;
     this.right = null;
     }
}
 
// helper function to create a new Node
function newNode(data)
{
    var temp = new Node();
    temp.data = data;
    temp.right = null;
    temp.left = null;
    return temp;
}
 
function KthLargestUsingMorrisTraversal(root , k)
{
    var curr = root;
    var Klargest = null;
 
    // count variable to keep count of visited Nodes
    var count = 0;
 
    while (curr != null)
    {
        // if right child is NULL
        if (curr.right == null)
        {
 
            // first increment count and
            // check if count = k
            if (++count == k)
                Klargest = curr;
 
            // otherwise move to the left child
            curr = curr.left;
        }
 
        else
        {
 
            // find inorder successor of
            // current Node
            var succ = curr.right;
 
            while (succ.left != null && succ.left != curr)
                succ = succ.left;
 
            if (succ.left == null)
            {
 
                // set left child of successor to the
                // current Node
                succ.left = curr;
 
                // move current to its right
                curr = curr.right;
            }
 
            // restoring the tree back to original binary
            // search tree removing threaded links
            else
            {
 
                succ.left = null;
 
                if (++count == k)
                    Klargest = curr;
 
                // move current to its left child
                curr = curr.left;
            }
        }
    }
    return Klargest;
}
 
// Driver code
  
    // Your JavaScript Code
    /* Constructed binary tree is
        4
        / \
       2 7
    / \ / \
    1 3 6 10 */
 
     root = newNode(4);
    root.left = newNode(2);
    root.right = newNode(7);
    root.left.left = newNode(1);
    root.left.right = newNode(3);
    root.right.left = newNode(6);
    root.right.right = newNode(10);
 
    document.write("Finding K-th largest Node in BST : " +
               KthLargestUsingMorrisTraversal(root, 2).data);
 
// This code contributed by aashish1995
 
</script>


Output

Finding K-th largest Node in BST : 7

Complexity Analysis:

  • Time Complexity : O(n) 
  • Auxiliary Space : O(1)


Previous Article
Next Article

Similar Reads

Sum of K largest elements in BST using O(1) Extra space
Given a BST, the task is to find the sum of all elements greater than or equal to K-th largest element in O(1) space.Examples: Input : K = 3 8 / \ 7 10 / / \ 2 9 13 Output : 32 Explanation: 3rd largest element is 9 so sum of all elements greater than or equal to 9 are 9 + 10 + 13 = 32. Input : K = 2 8 / \ 5 11 / \ 2 7 \ 3 Output : 19 Explanation: 2
9 min read
K'th smallest element in BST using O(1) Extra Space
Given a Binary Search Tree (BST) and a positive integer k, find the k'th smallest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 10, and if k = 5, then output should be 14. We have discussed two methods in this post and one method in this post. All of the previous methods require extra space. H
13 min read
Connect nodes at same level using constant extra space
Write a function to connect all the adjacent nodes at the same level in a binary tree. The structure of the given Binary Tree node is like following C/C++ Code struct node{ int data; struct node* left; struct node* right; struct node* nextRight; }; // This code is contributed by Yash Agarwal(yashagarwal2852002) C/C++ Code struct node { int data; st
15+ min read
Sort an array according to absolute difference with a given value "using constant extra space"
Given an array of n distinct elements and a number x, arrange array elements according to the absolute difference with x, i. e., element having minimum difference comes first and so on, using constant extra space. Note : If two or more elements are at equal distance arrange them in same sequence as in the given array.Examples: Input : arr[] = {10,
7 min read
Sum of all substrings of a string representing a number | Set 2 (Constant Extra Space)
Given a string representing a number, we need to get the sum of all possible sub strings of this string. Examples : Input : s = "6759" Output : 8421 sum = 6 + 7 + 5 + 9 + 67 + 75 + 59 + 675 + 759 + 6759 = 8421 Input : s = "16" Output : 23 sum = 1 + 6 + 16 = 23Recommended PracticeSum of all substrings of a numberTry It! We have discussed a solution
7 min read
Rearrange positive and negative numbers with constant extra space
Given an array of positive and negative numbers, arrange them such that all negative integers appear before all the positive integers in the array without using any additional data structure like a hash table, arrays, etc. The order of appearance should be maintained. Examples: Input: [12 11 -13 -5 6 -7 5 -3 -6] Output: [-13 -5 -7 -3 -6 12 11 6 5]R
15+ min read
Move all negative numbers to beginning and positive to end with constant extra space
An array contains both positive and negative numbers in random order. Rearrange the array elements so that all negative numbers appear before all positive numbers. Examples : Input: -12, 11, -13, -5, 6, -7, 5, -3, -6Output: -12 -13 -5 -7 -3 -6 11 6 5 Note: Order of elements is not important here. Naive approach: The idea is to sort the array of ele
15+ min read
K'th Largest Element in BST when modification to BST is not allowed
Given a Binary Search Tree (BST) and a positive integer k, find the k'th largest element in the Binary Search Tree. For example, in the following BST, if k = 3, then output should be 14, and if k = 5, then output should be 10. We have discussed two methods in this post. The method 1 requires O(n) time. The method 2 takes O(h) time where h is height
15+ min read
Kth smallest element in the array using constant space when array can't be modified
Given an array arr[] of size N having no duplicates and an integer K, the task is to find the Kth smallest element from the array in constant extra space and the array can't be modified. Examples: Input: arr[] = {7, 10, 4, 3, 20, 15}, K = 3 Output: 7 Given array in sorted is {3, 4, 7, 10, 15, 20} where 7 is the third smallest element. Input: arr[]
7 min read
Merge two sorted arrays in constant space using Min Heap
Given two sorted arrays, we need to merge them with O(1) extra space into a sorted array, when N is the size of the first array, and M is the size of the second array. Example : Input: arr1[] = {10}; arr2[] = {2, 3};Output: arr1[] = {2} arr2[] = {3, 10} Input: arr1[] = {1, 5, 9, 10, 15, 20}; arr2[] = {2, 3, 8, 13};Output: arr1[] = {1, 2, 3, 5, 8, 9
8 min read
Sorted subsequence of size 3 in linear time using constant space
Given an array, the task is to find three elements of this array such that they are in sorted form i.e. for any three elements a[i], a[j] and a[k], they follow this relationship: a[i] < a[j] < a[k] where i < j < k. This problem must be solved using constant space or no extra space. This problem is already solved in linear time using lin
9 min read
Create Balanced Binary Tree using its Leaf Nodes without using extra space
Prerequisites: Binary Tree to Doubly Linked ListGiven a Binary Tree, the task is to create a Balanced Binary Tree from all the leaf nodes of the given Binary Tree. Examples: Input: Output: 7 8 5 9 10 Explanation: Required balanced binary tree will be: Input: Output: 13 21 29 7 15 Explanation: Required balanced binary tree is: 29 / \ 21 7 / \ 13 15
15 min read
Find duplicates in constant array with elements 0 to N-1 in O(1) space
Given a constant array of n elements which contains elements from 1 to n-1, with any of these numbers appearing any number of times. Find any one of these repeating numbers in O(n) and using only constant memory space. Examples: Input : arr[] = {1, 2, 3, 4, 5, 6, 3} Output : 3 As the given array is constant methods given in below articles will not
12 min read
Count Possible Decodings of a given Digit Sequence in O(N) time and Constant Auxiliary space
Given a digit sequence S, the task is to find the number of possible decodings of the given digit sequence where 1 represents 'A', 2 represents 'B' ... and so on up to 26, where 26 represents 'Z'. Examples: Input: S = "121" Output: 3 The possible decodings are "ABA", "AU", "LA" Input: S = "1234" Output: 3 The possible decodings are "ABCD", "LCD", "
6 min read
Constant & Linear Space Complexity in Algorithms
Being a programmer, you might have solved a lot of programming challenges. In programming space and time complexity matters a lot when we need to execute a program. Our algorithm should be efficient, and it should take less time. Whenever you're writing a solution to a program, some memory is required to complete, and it is important for our progra
5 min read
Count the number of Nodes in a Binary Tree in Constant Space
Given a binary tree having N nodes, count the number of nodes using constant O(1) space. This can be done by simple traversals like- Preorder, InOrder, PostOrder, and LevelOrder but these traversals require an extra space which is equal to the height of the tree. Examples: Input: Output: 5Explanation: In the above binary tree, there are total 5 nod
10 min read
Remove extra edge from a BST
Given a Binary Search Tree where an arbitrary node has 2 parents. Delete the extra edge and return the fixed Binary Search Tree. Examples: Input: 7 / \ 6 10 / \ / \2 9 11 Output: 7 / \ 6 10 / / \2 9 11 Explanation: The edge between 6 and 9 should be removed because it has 2 parents and it is a BST after removing it. Input: 20 / \ 16 30 / \ 13 18 Ou
9 min read
k smallest elements in same order using O(1) extra space
We are given an array of n-elements you have to find k smallest elements from the array but they must be in the same order as they are in the given array and we are allowed to use only O(1) extra space. Examples: Input : arr[] = {4, 2, 6, 1, 5}, k = 3 Output : 4 2 1 Explanation : 1, 2 and 4 are three smallest numbers and 4 2 1 is their order in giv
8 min read
Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space
We have an array of the form {a0, a1, a2....., an, b0, b1, b2, .....bn} and our task is to rearrange the same in theform given below by using O(1) space- {a0, b0, a1, b1, a2, b2...........an, bn} Examples: Input : arr[] = {1, 3, 5, 7, 2, 4, 6, 8} Output : {1, 2, 3, 4, 5, 6, 7, 8} Input : arr[] = {11, 13, 15, 12, 14, 16} Output : {11, 12, 13, 14, 15
11 min read
Shuffle 2n integers as a1-b1-a2-b2-a3-b3-..bn without using extra space | Set 2
Given an array arr[] consisting of 2* N elements in the form of { a1, a2, â€Ķ, aN, b1, b2, ..., bN }, the task is to shuffle the array to {a1, b1, a2, b2, ..., an, b1} without using extra space. Examples : Input: arr[] = { 1, 3, 5, 2, 4, 6 }Output: 1 2 3 4 5 6Explanation: The output contains the elements in the form of { a1, b1, a2, b2, a3, b3 }. Inp
15 min read
Design a dynamic stack using arrays that supports getMin() in O(1) time and O(1) extra space
Design a special dynamic Stack using an array that supports all the stack operations such as push(), pop(), peek(), isEmpty(), and getMin() operations in constant Time and Space complexities. Examples: Assuming the right to left orientation as the top to bottom orientation and performing the operations: Push(10): 10 is added to the top of the stack
15+ min read
Check if a number is palindrome or not without using any extra space | Set 2
Given a number ‘n’ and our goal is to find out it is palindrome or not without using any extra space. We can’t make a new copy of number. Examples: Input: n = 2332Output: Yes it is Palindrome.Explanation:original number = 2332reversed number = 2332Both are same hence the number is palindrome. Input: n=1111Output: Yes it is Palindrome. Input: n = 12
5 min read
Duplicates in an array in O(n) time and by using O(1) extra space | Set-3
Given an array of n elements which contains elements from 0 to n-1, with any of these numbers appearing any number of times. Find these repeating numbers in O(n) and using only constant memory space. It is required that the order in which elements repeat should be maintained. If there is no repeating element present then print -1. Examples: Input :
10 min read
Print n x n spiral matrix using O(1) extra space
Given a number n, print a n x n spiral matrix (of numbers from 1 to n x n) in clockwise direction using O(1) space. Example : Input: n = 5 Output: 25 24 23 22 21 10 9 8 7 20 11 2 1 6 19 12 3 4 5 18 13 14 15 16 17 We strongly recommend you to minimize your browser and try this yourself first. The solution becomes simple if extra space is allowed. We
9 min read
Length of longest palindrome list in a linked list using O(1) extra space
Given a linked list, find the length of the longest palindrome list that exists in that linked list. Examples: Input : List = 2->3->7->3->2->12->24 Output : 5 The longest palindrome list is 2->3->7->3->2 Input : List = 12->4->4->3->14 Output : 2 The longest palindrome list is 4->4Recommended PracticeLeng
9 min read
Shuffle 2n integers in format {a1, b1, a2, b2, a3, b3, ......, an, bn} without using extra space
Given an array of 2n elements in the following format { a1, a2, a3, a4, ....., an, b1, b2, b3, b4, ...., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, ......, an, bn } without using extra space. Examples: Input : arr[] = { 1, 2, 9, 15 }Output : 1 9 2 15 Input : arr[] = { 1, 2, 3, 4, 5, 6 }Output : 1 4 2 5 3 6 Recommended: Please s
10 min read
To check a number is palindrome or not without using any extra space
Given a number 'n' and our goal is to find out it is palindrome or not without using any extra space. We can't make a new copy of the number . Examples: Input : 2332 Output : Yes it is Palindrome. Explanation: original number = 2332 reversed number = 2332 Both are same hence the number is palindrome. Input :1111 Output :Yes it is Palindrome. Input
6 min read
Reverse a stack without using extra space in O(n)
Reverse a Stack without using recursion and extra space. Even the functional Stack is not allowed. Examples: Input : 1->2->3->4 Output : 4->3->2->1 Input : 6->5->4 Output : 4->5->6 We have discussed a way of reversing a stack in the below post.Reverse a Stack using Recursion The above solution requires O(n) extra space
6 min read
Shuffle array {a1, a2, .. an, b1, b2, .. bn} as {a1, b1, a2, b2, a3, b3, â€Ķâ€Ķ, an, bn} without using extra space
Given an array of 2n elements in the following format { a1, a2, a3, a4, â€Ķ.., an, b1, b2, b3, b4, â€Ķ., bn }. The task is shuffle the array to {a1, b1, a2, b2, a3, b3, â€Ķâ€Ķ, an, bn } without using extra space.Examples : Input : arr[] = { 1, 2, 9, 15 } Output : 1 9 2 15 Input : arr[] = { 1, 2, 3, 4, 5, 6 } Output : 1 4 2 5 3 6 We have discussed O(n2) and
14 min read
Replace all occurrences of string AB with C without using extra space
Given a string str that may contain one more occurrences of "AB". Replace all occurrences of "AB" with "C" in str. Examples: Input : str = "helloABworld"Output : str = "helloCworld"Input : str = "fghABsdfABysu"Output : str = "fghCsdfCysu"A simple solution is to find all occurrences of "AB". For every occurrence, replace it with C and move all chara
10 min read