Kth Smallest and Largest element in BST

Binary Search Trees Medium Medium

Given the root node of a binary search tree (BST) and an integer k.

Return the kth smallest and largest value (1-indexed) of all values of the nodes in the tree.

Examples:

Input : root = [3,1,4,null,2] , k = 1

Output : [1, 4]

Explanation : The 1st smallest value in given BST is 1.

The 1st largest value in given BST is 4.

Input : root = [5, 3, 6, 2, null, null, null, 1] , k = 3

Output : [3, 3]

Explanation : The 3rd smallest value in given BST is 3.

The 3rd largest value in given BST is 3.

Input : root = [3,1,4,null,2] , k = 2

Constraints

  • The number of nodes in the tree is n.
  • 1 <= k <= n <= 104
  • 0 <= Node.val <= 105

Hints

  • Perform an inorder traversal while maintaining a counter. Stop when the k-th smallest element is found. Similarly, for k-th largest, perform a reverse inorder traversal.
  • Perform a full inorder traversal and store values in an array. The k-th smallest is at index k-1, and the k-th largest is at index n-k.

Company Tags

GE Healthcare Zomato Cloudflare Medtronic Swiggy Shopify Robinhood IBM Johnson & Johnson Alibaba Cerner Flipkart Bungie Lyft Electronic Arts PayPal Visa Red Hat Roche Boston Consulting Group Mastercard Activision Blizzard Reddit JPMorgan Chase American Express Google Microsoft Amazon Meta Apple Netflix Adobe