// Kth Smallest Element in a BST

// Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.

// Note:
// You may assume k is always valid, 1 ≤ k ≤ BST's total elements.

// Follow up:
// What if the BST is modified (insert/delete operations) often and you need to find the kth smallest frequently?
// How would you optimize the kthSmallest routine?

/**
 * 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}
 */



@@ -603,8 +603,549 @@
 %7D%0A */%0A%0A%0A
+%0A if(root)%7B%0A        var smaller = kthSmallest(root.left, k, counter);%0A        if(smaller !== undefined) return smaller;%0A        counter++;%0A        if(counter === k) return root.val;%0A        smaller = kthSmallest(root.right, k, counter );%0A        return smaller%0A    %7D%0A%0A// function helper(node, counter)%7B%0A    //     if(node)%7B%0A    //         helper(node.left, counter);%0A    //         counter++;%0A    //         if(counter === k) return node.val;%0A    //         helper(node.right, counter );%0A    //     %7D%0A    // %7D%0A    // return helper(root, 0);%0A

add first solution