美文网首页
230. Kth Smallest Element in a B

230. Kth Smallest Element in a B

作者: jluemmmm | 来源:发表于2021-10-16 11:01 被阅读0次

给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。

递归

  • 时间复杂度O(n),空间复杂度O(n)
  • Runtime: 80 ms, faster than 92.77%
  • Memory Usage: 45.5 MB, less than 28.49%
/**
 * 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) {
  const nums = inorder(root, []);
  return nums[k - 1];
};

var inorder = function(root, res) {
  if (!root) return res;
  inorder(root.left, res);
  res.push(root.val);
  inorder(root.right, res);
  return res;
}

迭代

  • 时间复杂度O(n),空间复杂度O(n)
  • Runtime: 76 ms, faster than 98.09%
  • Memory Usage: 44.6 MB, less than 54.73%
var kthSmallest = function(root, k) {
  let stack = [];
  let res = [];
  while (stack.length || root) {
    if (root) {
      stack.push(root);
      root = root.left;
    } else {
      root = stack.pop();
      res.push(root.val);
      if (res.length === k) {
        return res[k - 1];
      }
      root = root.right;
    }
  }
};

相关文章

网友评论

      本文标题:230. Kth Smallest Element in a B

      本文链接:https://www.haomeiwen.com/subject/qktkoltx.html