We read every piece of feedback, and take your input very seriously.
To see all available qualifiers, see our documentation.
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Difficulty: 中等
Related Topics: 树, 深度优先搜索, 二叉搜索树, 二叉树
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k个最小元素(从 1 开始计数)。
root
k
示例 1:
输入:root = [3,1,4,null,2], k = 1 输出:1
示例 2:
输入:root = [5,3,6,2,4,null,null,1], k = 3 输出:3
提示:
n
**进阶:**如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第 k 小的值,你将如何优化算法?
Language: JavaScript
/** * 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 res let count = 0 function traversal(node) { if (node !== null) { if (count < k) traversal(node.left) if (++count === k) res = node.val if (count < k) traversal(node.right) } } traversal(root) return res } // var kthSmallest = function(root, k) { // let arr = [] // function traversal (node) { // if (node !== null && arr.length < k) { // traversal(node.left) // arr.push(node.val) // traversal(node.right) // } // } // traversal(root) // return arr[k-1] // };
The text was updated successfully, but these errors were encountered:
No branches or pull requests
230. 二叉搜索树中第K小的元素
Description
Difficulty: 中等
Related Topics: 树, 深度优先搜索, 二叉搜索树, 二叉树
给定一个二叉搜索树的根节点
root
,和一个整数k
,请你设计一个算法查找其中第k
个最小元素(从 1 开始计数)。示例 1:
示例 2:
提示:
n
。**进阶:**如果二叉搜索树经常被修改(插入/删除操作)并且你需要频繁地查找第
k
小的值,你将如何优化算法?Solution
Language: JavaScript
The text was updated successfully, but these errors were encountered: