LeetCode 230. 二叉搜索树中第 K 小的元素
原题链接
简单
作者:
autumn_0
,
2024-09-25 17:51:11
,
所有人可见
,
阅读 2
/**
* 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, k;
void dfs(TreeNode root){
if(root == null) return ;
dfs(root.left);
if(k == 0) return ;
if(--k == 0) res = root.val;
dfs(root.right);
}
public int kthSmallest(TreeNode root, int k) {
this.k = k;
dfs(root);
return res;
}
}