问题描述
我正在尝试通过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;
}
}
但是,系统给了我“超出内存限制”错误消息,我的逻辑有问题还是反正我可以修复我的代码?预先感谢!
解决方法
您的逻辑可能还不错,但是由于获得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分析1,2 。
-
蛮力算法通常会被easy个问题接受。对于medium和hard问题,蛮力算法大多因Time Limit Exceeded(TLE)而失败,而因内存限制超出(MLE)错误而失败。