题目链接
牛客网 - 二叉搜索树的第k个结点
LeerCode 230题 - 二叉搜索树中第K小的元素
算法思路
讲到二叉搜索树,就要联想到它的中序遍历是有序的。所以只需要中序遍历二叉搜索树,答案就显而易见了
代码实现
/*
public class TreeNode {
int val = 0;
TreeNode left = null;
TreeNode right = null;
public TreeNode(int val) {
this.val = val;
}
}
*/
public class Solution {
int count=0;
TreeNode node = null;
TreeNode KthNode(TreeNode pRoot, int k) {
inorder(pRoot,k);
return node;
}
//中序遍历
private void inorder(TreeNode root,int k){
if(root == null || count > k){
return;
}
inorder(root.left,k);
//中序遍历代码操作
count++;
if(count==k){
node = root;
return;
}
inorder(root.right,k);
}
}