Given a binary search tree, write a function kthSmallest to find the kth smallest element in it.
Note:
You may assume k is always valid, 1 ≤ k ≤ BST’s total elements.
Example 1:
Input: root = [3,1,4,null,2], k = 1
3
/ \
1 4
\
2
Output: 1
输出二叉树中第K大的节点值
思路:
考虑到中序遍历是按顺序输出的,所以中序遍历,并记录count,当k==count时返回,
为了及时终止遍历,返回boolean类型
//1ms
class Example {
int count = 1;
int res = 0;
public int kthSmallest(TreeNode root, int k) {
inorder(root, k);
return res;
}
public boolean inorder(TreeNode root, int k) {
if (root == null) {
return false;
}
if(inorder(root.left, k)) {
return true;
};
if (k == count) {
res = root.val;
return true;
}
count ++;
if(inorder(root.right, k)) {
return true;
}
return false;
}
}