给定一个二叉搜索树,编写一个函数 kthSmallest 来查找其中第 k 个最小的元素。
说明:
你可以假设 k 总是有效的,1 ≤ k ≤ 二叉搜索树元素个数。
示例 1:
输入: root = [3,1,4,null,2], k = 1
3
/
1 4
2
输出: 1
示例 2:
输入: root = [5,3,6,2,4,null,null,1], k = 3
5
/
3 6
/
2 4
/
1
输出: 3
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/kth-smallest-element-in-a-bst
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
利用二叉搜索树的性质可以中中序遍历法
/**
-
Definition for a binary tree node.
-
public class TreeNode {
-
int val; -
TreeNode left; -
TreeNode right; -
TreeNode(int x) { val = x; } -
}
*/class Solution {private int res, count;
public int kthSmallest(TreeNode root, int k) {
count = k;
inorder(root);
return res;
}
private void inorder(TreeNode root) {
if(root == null || count == 0) return;
inorder(root.left);
if(–count == 0) res = root.val;
inorder(root.right);
}
}
本文介绍了一个在二叉搜索树中查找第K个最小元素的算法。通过中序遍历的方法,利用二叉搜索树的性质,有效地找到目标元素。示例包括了具体的输入输出情况。
584

被折叠的 条评论
为什么被折叠?



