230. 二叉搜索树中第K小的元素

https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst/

  • inorder - iteration
  • inorder - recursion
  • countNode
  • priority queue
  • avl

inorder

  • iteration
  1. let kthsmall = function (root,k){
  2. let stack = [];
  3. while(root !== null || stack.length){
  4. while(root !== null){
  5. stack.push(root);
  6. root = root.left
  7. }
  8. root = root.pop();
  9. --k;
  10. if(k==0){
  11. break;
  12. }
  13. root = root.right;
  14. }
  15. return root.val;
  16. }
  • recursion
  1. to be continued

countnode

  1. function countNode (root) {
  2. if(root == null) return 0;
  3. let l = countNode(root.left);
  4. let r = countNode(root.right);
  5. return l+r+1;
  6. }
  7. let kthSmall = (root,k)=>{
  8. let c = countNode(root.left);
  9. if(c == k-1)return root.val;
  10. else if(c<k-1) return kthSmal(root.right,k-c-1);
  11. return kthSmall(root.left,k)
  12. }