-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
47 lines (42 loc) · 1.07 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
const { make_tree } = require('../utils');
const test = make_tree([5,3,6,2,4,null,null,1], [0])[0];
/**
* Definition for a binary tree node.
* function TreeNode(val) {
* this.val = val;
* this.left = this.right = null;
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
return kthSmallestHelp(root);
function kthSmallestHelp(root) {
if (root.left) {
const in_left = kthSmallestHelp(root.left);
if (in_left !== undefined) {
return in_left;
}
}
k--;
if (k === 0) {
return root.val;
}
if (root.right && k > 0) {
const in_right = kthSmallestHelp(root.right);
if (in_right !== undefined) {
return in_right;
}
}
}
};
console.log(kthSmallest(test, 3));
module.exports = {
title:'Kth Smallest Element in a BST',
id:'230',
difficulty:'medium',
url:'https://leetcode.com/problems/kth-smallest-element-in-a-bst/',
};