I was trying to solve this problem from leetcode and the prompt looks like this:
Given a binary search tree, write a function kthSmallest to find the kth smallest element in it. 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;
}
}
However, the system gave me the "memory limit exceeded" error message, is my logic faulted or is there anyway I could fix my code? Thanks in advance!
list.addAll(inOrder(root));== infinite recursion. Should just be adding the root node here. - Jim Garrison