题目描述
给定一个二叉搜索树的根节点 root ,和一个整数 k ,请你设计一个算法查找其中第 k 个最小元素(从 1 开始计数)。
样例描述
思路
中序遍历 + BST性质
转化为求中序遍历的第k个数,因为BST的中序遍历是升序有序的
有给定值的话,一般用减法,然后要设置成全局变量
代码
/**
* 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 res = 0;
//全局
int t;
public int kthSmallest(TreeNode root, int k) {
t = k;
dfs(root);
return res;
}
public void dfs(TreeNode root) {
if (root == null) {
return;
}
dfs(root.left);
t --;
if (t == 0) {
res = root.val;
}
dfs(root.right);
}
}