我在找英国夏令时第十小的。
public void findKthSmallest(BSTNode<T> node, int k) {
if(node == null)
return;
findKthSmallest(node.left, k);
count++;
if (k == count) {
System.out.println("Kth smallest: " + node.data);
return;
}
findKthSmallest(node.right, k);
}
这里count是一个实例变量我不知道如何在函数中使用count作为参数(local varaible)来实现它,因为当函数返回时它会得到重置。
知道吗??
最佳答案
因为这是Java,而且没有按引用传递,我认为最简单的方法是修改findKthSmallest
以返回根在node
的子树中有多少节点像这样的:
public int findKthSmallest(BSTNode<T> node, int k) {
if(node == null)
return 0;
int left = findKthSmallest(node.left, k);
if (k == left + 1) {
System.out.println("Kth smallest: " + node.data);
return 1;
}
return 1 + left + findKthSmallest(node.right, k);
}
关于algorithm - 使用递归顺序在bst中找到最小的kth,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11070553/