230. Kth Smallest Element in a BST

Given the root of a binary search tree, and an integer k, return the kth smallest value (1-indexed) of all the values of the nodes in the tree.

DFS搜索,遍历的时候更新全局变量count。
采用中序搜索,当count等于k时,将全局变量ans设置为root.val。
搜索完毕返回ans。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
/**
* 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 ans;
int count;
public int kthSmallest(TreeNode root, int k) {
ans = -1;
count = 0;
dfs(root,k);
return ans;
}

private void dfs(TreeNode root, int k){
if(root == null){
return;
}
dfs(root.left,k);
count++;
if (k == count){
ans = root.val;
}
dfs(root.right,k);
}
}
Author

Xander

Posted on

2022-04-18

Updated on

2022-04-18

Licensed under

Comments