在BST中找到Kth最小值-K不变

问题描述

我已经考虑了很久,它一直在炸我的大脑。可能我还不太了解递归。

我不明白为什么k的值等于0时不进入负数。而是在助手功能存在之前一直保持为0。我尝试传入一个初始值为零的整数并相加直到其值等于k。但是,这导致了同样的问题,一旦它等于k,就保持这种状态。

有人可以解释为什么值保持不变吗?

> -------------+-------------+------------+
> --  Code  -- | -- Value -- | -- Date -- | 
> -------------+-------------+------------+
>    ZZ-100    |      90     |     ?      | 
> -------------+-------------+------------+
>    ZZ-200    |     115     |     ?      |
> -------------+-------------+------------+
>    ZZ-300    |      10     |     ?      |

例如,对于预期输出下面的树为1。但是我得到3,控制台打印两次。

var query = Table1                      
        .Join(Table2.Where(w => (w.State == 1)),h => new { h.IdGroup1,h.IdGroup2 },p => new { p.IdGroup1,p.IdGroup2 },(h,p) => new { h,p })                    
        .Join(Table3.Where(w => (w.Protocol == "TCP")),pt => pt.p.NameProtocol,p => p.NameProtocol,(pt,p) => new { pt,p })          
        .GroupBy(gb => new { gb.pt.p.Code })            
        .OrderBy(ob => ob.Key.Code)
        .Select(s => new {  Code = s.Key.Code,Value = (double?)s.Min(a => a.pt.h.Value) })
        .ToList();

解决方法

我认为问题是因为您在每个递归调用中传递了k。您不应该这样做,因为这会导致每个递归调用都获得自己的k副本。这意味着当您修改k时:

k = k - 1;

堆栈中的其他调用不知道k的更改。就其他调用而言,k仍为1,因为它们每个都有自己的副本。

要解决此问题,您应该有一个共享 k,所有递归调用都可以访问:

    static int sharedK; // shared!
    public int kthSmallest(TreeNode t,int k) {
      TreeNode tempNode = new TreeNode();
      sharedK = k; // setting the sharedK
      getKValue(t,tempNode); 
      return tempNode.val;
    }
    
    private static void getKValue(TreeNode t,TreeNode temp) {
        if(t == null) {
            return;
        }

        getKValue(t.left,temp);
        
        sharedK--; // note the change here
        System.out.println(sharedK);
        if(sharedK == 0) {
            temp.val = t.val;
            return;
        }
        getKValue(t.right,temp);
    }

如果通过引用传递k也可以实现相同的目的,但是不幸的是,您无法在Java中通过引用传递。

,

我认为问题需要您输出BST的第K个最小元素,这是使用O(N)存储空间的代码,其中N是BST中的节点数。首先,我们将使用有序遍历(递归)遍历BST,并将节点保存在数组或向量中。 BST的有序遍历使节点按排序顺序。

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
};

vector<int> nodes;

void inorder(TreeNode *root) {
    if(root!=NULL)
    {
        inorder(root->left);
        nodes.push_back(root->val);
        inorder(root->right);
    }
}
class Solution {
public:
    int getValue(TreeNode* root,int K)
    {
        nodes.clear();
        if(root!=NULL)
        {
            inorder(root);
            return nodes[K-1];
        }
        return -1;
    }
};