Giving right output as custom but incorrect when submitting


#1

For the test case, `5 3 2 -1 -1 -1, 2’, My code is giving the right output for custom input but is giving a different output when submitting the code. Please check this and let me know the issue.


#2

You might be using global variables. Try resetting all the variables as the first thing that happens when the method is called.


#3

Samething is happening with me too. My solution is right and In my opinion the output which is expected as per the test is wrong.
For input
5 3 -1 4 -1 -1
2
Output should be 3 and not 4 (which test expects).
Here’s my code:
public class Solution {
public int kthsmallest(TreeNode A, int B) {
TreeNode root = A;
int result = Integer.MIN_VALUE;
int nodeVal = Integer.MIN_VALUE;
if(root == null) {
return result;
}
Deque stack = new ArrayDeque();
while(true) {
while(root != null) {
stack.push(root);
root = root.left;
}
TreeNode tempNode = stack.poll();
nodeVal = tempNode.val;
if(B != 0 && nodeVal > result) {
result = nodeVal;
–B;
} else {
break;
}
if(stack.size() == 0) {
break;
}
if(tempNode.right != null) {
stack.push(tempNode.right);
}
}
return result;
}
}


#4

No need to write such a complex code apply simple idea. And the idea is that inOreder traversel of binary tree gives you sorted order of element which is sorted in ascending order.
Thanks


#5

use global variables and reset them in main function.
like int total=0 is global, you again make total=0 in beginning of main.


#6

but answer should be 3 not 4. right??