230. Kth Smallest Element in a BST


BST, and kth , order problem => think about inorder traversal
but be careful, the global variable count is necessary! (if use recursion)
or the result will change in the recursion process again
in this ex, k will pass into inorder(), twice, and all are k = 1, so k-- , k == 0, there will be two times get the result, and the second will replace the first result!

even if you dont use global result, the behavior is the same, k = 1 pass to inorder twice

traversal 都是遍例所有節點, 所以是 O(n), 因為 recursive 所以空間也需要 O(n)
use count!
time: O(n)
space: O(n)
stack - iteration
latest
early stop, if find k, we won't keep going, so
T: O(k)
Last updated
Was this helpful?