版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/zxm1306192988/article/details/82023273
牛客这里写链接内容
题目描述
给定一棵二叉搜索树,请找出其中的第k小的结点。例如, (5,3,7,2,4,6,8) 中,按结点数值大小顺序第三小结点的值为4。
题解;
由于是二叉搜索树,其中序遍历序列就是从小到大的序列,所以中序遍历二叉搜索树,用一个全局遍历记录访问结点的次数,如果等于 k , 则当前遍历的结点就是 第 k 小的结点,返回。
public class Solution {
TreeNode result;
int count = 0;
TreeNode KthNode(TreeNode pRoot, int k) {
robot(pRoot, k);
return result;
}
private void robot(TreeNode node, int k) {
if (node == null) {
return;
}
if (node.left != null) {
robot(node.left, k);
}
count++;
if (count == k) {
result = node;
return;
}
if (node.right != null) {
robot(node.right, k);
}
}
}