code.ashish.me

Atom feed

Recently added: 128 Longest Consecutive Sequence, 347 Top K Frequent Elements, 045 Jump Game 2, 228 Summary Ranges, 219 Contains Duplicate 2

230 Kth Smallest Element In A Bst

/**
 *
 * Ashish Patel
 * e: ashishsushilPatel@gmail.com
 * w: https://ashish.me
 *
 */

function TreeNode(val) {
  this.val = val
  this.left = this.right = null
}

const kthSmallestElementInABst = (root, k) => {
  let result = 0
  let count = 0
  const traverse = (root, k) => {
    if (!root) {
      return
    }
    traverse(root.left, k)
    count++
    if (count == k) {
      result = root.val
    }
    traverse(root.right, k)
  }
  traverse(root, k)
  return result
}

test('kthSmallestElementInABst', () => {
  const t1 = new TreeNode(3)
  t1.left = new TreeNode(1)
  t1.right = new TreeNode(4)
  t1.left.right = new TreeNode(2)
  expect(kthSmallestElementInABst(t1, 1)).toEqual(1)
})

Created 2021-01-31T05:24:55+05:30 · Edit