Finding Kth Smallest Element in a BST
Sat Mar 09 2024
printKthSmallest :
method in the BST class to find the kth smallest element in a Binary Search Tree. By leveraging the in-order traversal, which inherently produces a sorted sequence of the BST elements, the method efficiently accesses the kth element in this sequence.
1class Node {
2  constructor(data) {
3    this.data = data;
4    this.right = null;
5    this.left = null;
6  }
7}
8
9class BST {
10  constructor() {
11    this.root = null;
12  }
13  insert(val) {
14    const newNode = new Node(val);
15    if (!this.root) {
16      this.root = newNode;
17      return;
18    }
19    let current = this.root;
20    while (current) {
21      if (val < current.data) {
22        if (!current.left) {
23          current.left = newNode;
24          return;
25        }
26        current = current.left;
27      } else if (val > current.data) {
28        if (!current.right) {
29          current.right = newNode;
30          return;
31        }
32        current = current.right;
33      } else {
34        return;
35      }
36    }
37  }
38  printInOrder(node = this.root) {
39    if (!node) return [];
40    return [
41      ...this.printInOrder(node.left),
42      node.data,
43      ...this.printInOrder(node.right),
44    ];
45  }
46  printKthSmallest(node = this.root, k) {
47    if (!node) return [];
48    let arr = this.printInOrder(node);
49    return arr[k];
50  }
51}
52const tree = new BST();
53tree.insert(5);
54tree.insert(3);
55tree.insert(7);
56tree.insert(2);
57tree.insert(4);
58tree.insert(6);
59tree.insert(8);
60//console.log(tree.printInOrder())
61console.log(tree.printKthSmallest(tree.root, 2));
62