Recursion 用递归方法编写迭代法

Recursion 用递归方法编写迭代法,recursion,binary-search-tree,Recursion,Binary Search Tree,我正在做二叉搜索树作业,我被要求将递归方法转换为迭代方法。这是递归方法,下面是我的迭代方法。此方法应返回包含第k个键的节点。我的方法一直给我一个NullPointerException,我不知道为什么。多谢各位 提供的代码: public Key select(int k) { Node node = select(root, k); if (node==null) { return null; } else { return node.k

我正在做二叉搜索树作业,我被要求将递归方法转换为迭代方法。这是递归方法,下面是我的迭代方法。此方法应返回包含第k个键的节点。我的方法一直给我一个NullPointerException,我不知道为什么。多谢各位

提供的代码:

public Key select(int k) {
    Node node = select(root, k);
    if (node==null) {
        return null;
    } else {
        return node.key;
    }
}

// Return Node containing kth key (zero based)
private Node select(Node node, int k) { 
    if (node == null) return null;

    int t = size(node.left);
    if (t > k)
        return select(node.left, k);
    else if (t < k)
        return select(node.right, k - t - 1);
    else
        return node;
}   
公钥选择(int k){
节点=选择(根,k);
if(node==null){
返回null;
}否则{
返回node.key;
}
}
//包含第k个键的返回节点(基于零)
专用节点选择(节点节点,int k){
如果(node==null)返回null;
int t=大小(节点左侧);
如果(t>k)
返回选择(node.left,k);
else if(t

我的代码:

public Key selectI(int k) {
    return selectI(root, k);
}

private Key selectI(Node node, int k) {
    Node curr = node;
    while (curr != null) {
          int t = size(node.left);
          if (t > k) {
               curr = node.left;
          } else if (t < k) {
               curr = node.right;
               k = (k - (t - 1));

          } else
               return curr.key;
    }
    return null;
}
公钥选择i(int k){
返回selectI(根,k);
}
私钥选择i(节点,int k){
节点电流=节点;
while(curr!=null){
int t=大小(节点左侧);
如果(t>k){
curr=node.left;
}else if(t
问题似乎是您没有更新k的值。这通常是递归完成的,但如果要生成一个迭代函数,就必须从数学角度来完成。当传递到左侧(t>k)时,将继续搜索大小为k的节点。当您向右传递(t
还要确保不断更新正在查看的当前节点的大小。您不希望只查看树的大小,这会破坏t和k值之间的数学关系,这将导致程序运行,直到没有更多节点可查看

为什么在选择正确的节点时给出
k-t-1
?@AbbasGabru它与原始递归代码一起提供。这是一个好问题,我也不知道为什么会这样。这里有一个递归代码示例,它也使用k-t-1来选择正确的节点。如果有人能帮助回答这个问题,我将不胜感激。这是您所写的`此方法应返回包含第k个键的节点。`但您提供的代码是返回包含第k个最小键的节点的代码。。。。所以我想问的是,如果您返回的是包含密钥的节点,则无需(在您的代码中)递减它。@AbbasGabru我已对上面的代码进行了更改。我测试了我的代码,没有减少它,但这使我处于一个无限循环中。我已经尝试在我的代码中递增t,现在就是我现在所在的位置,它只返回根之后的第一个值。在BST中,使用以下数字[5,50,20,78]返回50,而我希望它返回78。有什么想法吗?谢谢。我删除了一些不需要的变量,从而清理了代码。然而,我得到了NullPointerException。每当我从“curr=node.right;”更改为“curr=curr.right;”时,似乎就会发生这种情况。谢谢你的建议。我想确保我正确地理解你。那么我是否需要同时更新t,大小和k,我们在if和else语句中寻找的节点?当传递到左侧时,我是否不需要更新k,但当传递到右侧时,我是否需要将k更新为k=(k-(t-1))?谢谢!根据你的建议,我解决了这个问题。