Leetcode 230 - Kth smallest element in a bst

Note:

  • As it’s a BST tree, so its inorder traversal is a sorted array.

Question:

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree

Example:

img

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

Code:

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
/**
* Definition for a binary tree node.
* function TreeNode(val, left, right) {
* this.val = (val===undefined ? 0 : val)
* this.left = (left===undefined ? null : left)
* this.right = (right===undefined ? null : right)
* }
*/
/**
* @param {TreeNode} root
* @param {number} k
* @return {number}
*/
var kthSmallest = function(root, k) {
let traversal = [];
inorder(root);
return traversal[k-1];

function inorder(node) {
if (!node) return;
inorder(node.left);
traversal.push(node.val);
inorder(node.right);
}
};