【问题标题】:find kth smallest in bst using recursive inorder使用递归顺序在 bst 中找到第 k 个最小的
【发布时间】:2012-06-17 10:15:29
【问题描述】:

我试图在 BST 中找到第 k 个最小的。

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 作为参数(局部变量)来实现它,因为它会在函数返回时重置。

有什么想法吗??

【问题讨论】:

    标签: algorithm binary-search-tree inorder


    【解决方案1】:

    由于这是 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);
    }
    

    【讨论】:

      【解决方案2】:

      我想对 IVlad 的方法做一个小的修正。当我们向左搜索时,问题是找到第 k 个最小的。但是,向右搜索时,我们需要找到 k-left-1(丢弃左子树+当前节点)。在java中,除了创建一个类之外,我们不能返回多个值。所以通过传递一个数组作为参数来解决这个问题。代码如下:

      public int kthSmallest(TreeNode node, int k, TreeNode kthNode[]) {
          int leftCount = 0;
          int rightCount = 0;
          if(node.left!=null) {
              leftCount = kthSmallest(node.left, k, kthNode);
          }
          if(leftCount==k-1) {
              kthNode[0] = node; // We can also return from here
          }
          if(node.right!=null) {
              rightCount = kthSmallest(node.right, k-leftCount-1, kthNode);
          }
          return leftCount + 1 + rightCount;
      }
      
      public TreeNode kthSmallest(TreeNode node, int k) {
          TreeNode kNode[] = new TreeNode[1];
          int nodeCount = kthSmallest(node, k, kNode);
          return kNode[0];
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-01-06
        • 1970-01-01
        • 2013-01-04
        • 2021-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-03-02
        相关资源
        最近更新 更多