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
给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个 最小的元素。
kthSmallest
k
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
Input: root = [3,1,4,null,2], k = 1 3 / \ 1 4 \ 2 Output: 1
Input: root = [5,3,6,2,4,null,null,1], k = 3 5 / \ 3 6 / \ 2 4 / 1 Output: 3
The text was updated successfully, but these errors were encountered:
/** * 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 result; inorderTravel(root); return result; function inorderTravel(root) { if (result !== undefined || root === null) { return; } inorderTravel(root.left); if (--k === 0) { result = root.val; return; } inorderTravel(root.right); } };
/** * 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 result; let patrol = root; const stack = []; while (stack.length !== 0 || patrol !== null) { while (patrol !== null) { stack.push(patrol); patrol = patrol.left; } patrol = stack.pop(); if (--k === 0) { result = patrol.val; break; } patrol = patrol.right; } return result; };
Sorry, something went wrong.
No branches or pull requests
230. Kth Smallest Element in a BST
给定一个二叉搜索树,编写一个函数
kthSmallest
来查找其中第k
个 最小的元素。你可以假设
k
总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。Example 1
Example 2
The text was updated successfully, but these errors were encountered: