题目描述
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
样例描述
思路
中序遍历 + BST性质
转化为求中序遍历的第k个数,因为BST的中序遍历是升序有序的
为了提前返回,可以将dfs设置成布尔型,表示是否搜到结果
代码
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode() {}
* TreeNode(int val) { this.val = val; }
* TreeNode(int val, TreeNode left, TreeNode right) {
* this.val = val;
* this.left = left;
* this.right = right;
* }
* }
*/
class Solution {
int idx = 0, t;
int res = 0;
public int kthSmallest(TreeNode root, int k) {
t = k;
dfs(root);
return res;
}
//表示是否搜到,为了提前返回
public boolean dfs(TreeNode root) {
if (root == null) return false;
if (dfs(root.left)) return true;
idx ++;
if (idx == t) {
res = root.val;
return true;
}
return dfs(root.right);
}
}