Kth Largest/Smallest Element in Binary Search Tree using JavaScript
Last Updated :
26 Mar, 2024
A binary search tree is a type of binary tree in which each node has two children: left child & right child. In a Binary search tree (BST) all nodes in the left subtree have values less than the node value and all nodes in the right subtree have values greater than the node value.
Different approaches to find the Kth largest/smallest element in a Binary Search Tree are
Using In-order Traversal
We will create a function to perform an in-order traversal of a BST, storing elements in ascending order. Then, another function, kthLargestAndSmallest, will use this traversal to find the kth smallest and largest elements in the tree.
Example: The below code traverse the BST in the in-order manner to find kth largest and smallest elements.
JavaScript
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function inorderTraversal(root, inorder) {
if (!root) return;
inorderTraversal(root.left, inorder);
inorder.push(root.val);
inorderTraversal(root.right, inorder);
}
function kthLargestAndSmallest(root, k) {
const inorder = [];
inorderTraversal(root, inorder);
const n = inorder.length;
if (k > n || k <= 0) {
return null;
}
const kthSmallest = inorder[k - 1];
const kthLargest = inorder[n - k];
return { kthSmallest, kthLargest };
}
const root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(6);
root.left.right = new TreeNode(4);
root.left.left = new TreeNode(2);
root.right.right = new TreeNode(8);
console.log(kthLargestAndSmallest(root, 2));
Output{ kthSmallest: 3, kthLargest: 6 }
Time Complexity: O(n)
Space Complexity: O(n)
Iterative Approach
We will define two functions, kthSmallest and kthLargest, both utilizing iterative in-order traversal with a stack. In kthSmallest, we traverse left until no more left child, decrementing k until it's 0, then return the current node value. Similarly, in kthLargest, we traverse right until no more right child, decrementing k until it's 0, then return the current node value.
Example: The below code iteratively traverses the BST and returns kth largest and smallest elements.
JavaScript
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function kthSmallest(root, k) {
const stack = [];
let curr = root;
while (curr || stack.length) {
while (curr) {
stack.push(curr);
curr = curr.left;
}
curr = stack.pop();
k--;
if (k === 0) return curr.val;
curr = curr.right;
}
return null;
}
function kthLargest(root, k) {
const stack = [];
let curr = root;
while (curr || stack.length) {
while (curr) {
stack.push(curr);
curr = curr.right;
}
curr = stack.pop();
k--;
if (k === 0) return curr.val;
curr = curr.left;
}
return null;
}
const root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(6);
root.left.right = new TreeNode(4);
root.left.left = new TreeNode(2);
root.right.right = new TreeNode(8);
console.log(kthLargest(root, 2));
console.log(kthSmallest(root, 2));
Time Complexity : O(h+k) , where h is height of BST.
Space Complexity : O(h)
Using Recursive Approach
We will define a function, inorderTraversal, to recursively perform an in-order traversal of the BST. Then, in kthSmallest, we will use this traversal to populate an array with elements in ascending order and return the kth element. Similarly, in kthLargest, we will populate the array in reverse order and return the kth element for the largest.
Example: The below code implements recursive in-order traversal to traverse the tree and find specified elements.
JavaScript
class TreeNode {
constructor(val) {
this.val = val;
this.left = null;
this.right = null;
}
}
function inorderTraversal(root, arr) {
if (!root) return;
inorderTraversal(root.left, arr);
arr.push(root.val);
inorderTraversal(root.right, arr);
}
function kthSmallest(root, k) {
const inorder = [];
inorderTraversal(root, inorder);
return inorder[k - 1];
}
function kthLargest(root, k) {
const inorder = [];
inorderTraversal(root, inorder);
return inorder[inorder.length - k];
}
const root = new TreeNode(5);
root.left = new TreeNode(3);
root.right = new TreeNode(6);
root.left.right = new TreeNode(4);
root.left.left = new TreeNode(2);
root.right.right = new TreeNode(8);
console.log(kthLargest(root, 2));
console.log(kthSmallest(root, 2));
Time Complexity : O(n)
Space Complexity : O(n)
Similar Reads
Find the Mode in a Binary Search Tree using JavaScript One can find the mode in a binary search tree using JavaScript. The mode in the binary search tree will be the value of the node that occurs with the highest frequency among all the nodes in the tree. If there is more than one mode present in the binary search tree then return all modes present in t
3 min read
LCA in Binary Tree using JavaScript The lowest common ancestor between two nodes n1 and n2 in a binary tree is defined as the lowest node in a Tree that has both n1 and n2 as descendants. If either n1 or n2 is not present in the tree, or if they are not connected through a common ancestor, the LCA of the binary tree is NULL. Below is
4 min read
Kth Ancestor in Binary Tree using JavaScript Given a binary tree and a node in this tree, our task is to find the k-th ancestor of the specified node in JavaScript. If no such ancestor exists, or when k exceeds the depth of the node, the function should return null. Example: Input: Node = 5, k = 2Output: 1ApproachFirst, calculate the depth of
2 min read
Detecting the Largest Element in an Array of Numbers (nested) in JavaScript Given a nested array of numbers, we need to find and return the largest element present in the array. Below are the approaches to detecting the largest element in an array of Numbers (nested) in JavaScript: Table of Content Iterative ApproachRecursive ApproachIterative ApproachUse a nested loop to t
3 min read
Return the Leftmost Value in the Last Row of the Binary Tree using JavaScript Given the root of a binary tree, our task is to return the leftmost value in the last row of the binary tree in JavaScript. Here we use recursive and iterative approaches to return the leftmost value in the last row. Explanation: The image below illustrates the leftmost value in the last row of the
3 min read
Search a Given Key in BST using JavaScript Given a binary search tree and a key, determine if the key is present in the tree. If the key is present, return the node containing the key otherwise, return null. Example: Input : {15,20,10,8,12,16,25}, Key : 20Output : 20 found 15 / \ 10 20 / \ / \ 8 12 16 25Table of Content Recursive ApproachIte
3 min read