【问题标题】:Finding the kth smallest element in the binary search tree在二叉搜索树中找到第 k 个最小的元素
【发布时间】:2020-08-16 03:49:38
【问题描述】:

我试图从 leetcode 解决这个问题,提示如下:

给定一棵二叉搜索树,编写一个函数 kthSmallest 来查找其中的第 k 个最小元素。 https://leetcode.com/problems/kth-smallest-element-in-a-bst/description/

class Solution {
   public int kthSmallest(TreeNode root, int k) {
       TreeNode curr = new TreeNode(0);
       ArrayList<TreeNode> res = new ArrayList<TreeNode>();
       res = inOrder(root);
       if(res != null){
           curr = res.get(k);
           return curr.val;
       }
       return -1; //if not found
   }
   
   public ArrayList<TreeNode> inOrder(TreeNode root){ //the value of the nodes would be in increasing order 
       ArrayList<TreeNode> list = new ArrayList<TreeNode>();
       if(root == null){
           return list;
       }
       list.addAll(inOrder(root.left));
       list.addAll(inOrder(root));
       list.addAll(inOrder(root.right));
       return list;
   }
}

但是,系统给了我“超出内存限制”错误消息,是我的逻辑有问题还是我可以修复我的代码?提前致谢!

【问题讨论】:

标签: java binary-search-tree inorder


【解决方案1】:

您的逻辑可能没问题,但应该是效率问题,因为您正在获得 MLE。您似乎使用了两个额外的空格,我们不需要它来解决这个问题。

这将在 Java 中传递:

public final class Solution {
    private static int res = 0;
    private static int count = 0;

    public final int kthSmallest(
        final TreeNode root, 
        final int k
    ) {
        count = k;
        inorder(root);
        return res;
    }

    private final void inorder(
        final TreeNode node
    ) {
        if (node.left != null)
            inorder(node.left);
        count--;
        if (count == 0) {
            res = node.val;
            return;
        }
        if (node.right != null)
            inorder(node.right);
    }
}

如果您有兴趣,这里有一个 Python 版本,与 inorder 遍历类似:

class Solution:
    def kthSmallest(self, root, k):
        def inorder(node):
            if not node:
                return
            inorder(node.left)
            self.k -= 1
            if self.k == 0:
                self.res = node.val
                return
            inorder(node.right)

        self.k, self.res = k, None
        inorder(root)
        return self.res

参考文献

  • 有关更多详细信息,请参阅Discussion Board,您可以在其中找到大量解释清楚且公认的解决方案,其中包含各种languages,包括低复杂度算法和渐近算法runtime/memory 分析@ 987654325@, 2.

  • 蛮力算法通常会被easy 问题接受。对于mediumhard 问题,蛮力算法大多会因Time Limit Exceeded (TLE) 而失败,而因超出内存限制 (MLE) 错误而失败的次数较少。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-01-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多