In the algorithm problem "Find the Kth Smallest Element in a BST" (https://leetcode.com/problems/kth-smallest-element-in-a-bst), my solution is below:
public class Solution {
private int count;
public int kthSmallest(TreeNode root, int k) {
if (root == null)
return 0;
int kth = kthSmallest(root.left, k);
if (count == k)
return kth;
/********** section A *************/
else if (++count == k)
return root.val;
/********** section A end *********/
/********** section B *************/
/*
else if (count == k - 1)
return root.val;
count++;
*/
/********** section B end *********/
/********** section C *************/
/*
else if (count == k - 1) {
count++;
return root.val;
}
*/
/********** section C end *********/
return kthSmallest(root.right, k);
}
}
In the leetcode online judge, section A is right and section B is wrong, which I think are equal to each other, I could not figure out the difference between the two sections.
P.S. Added the section C.
In section A
count increase no matter
++count == kis true of false.In section B
count only increases when
count == k - 1is false, because when thecount == k - 1is true, the function will return and no longer execute any more. But Since we have got the right value returned, is it necessary to increase the value of count?In section C
count updated only when
count == k - 1Conclusion Section B is not equal to A, neither section C, when I integrated section B with section C, as showed below:
else if (count == k - 1) { count++; return root.val; } count++;
it is equal to section A and passed the online judge, which is not elegant as section A.
:)
elsestatement below. Is that what you want to know? - CodebenderBwould be same as sectionAif you would movecount++;line before return statement. - Pshemo