您的位置:首页 > 编程语言 > Java开发

Leetcode腾讯精选_编号:230 --java

2019-03-01 23:13 417 查看

给定一个二叉搜索树,编写一个函数 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

/**
* Definition for a binary tree node.
* public class TreeNode {
*     int val;
*     TreeNode left;
*     TreeNode right;
*     TreeNode(int x) { val = x; }
* }
*/
class Solution {
private int count;
public int kthSmallest(TreeNode root, int k) {
int res=0;
if (root == null) {
return res;
}
res=kthSmallest(root.left,k);
if (count==k)
{
return res;
}
count++;
if (count==k)
{
return root.val;
}
return kthSmallest(root.right, k);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: