Monday, November 6, 2017

Special case of Leetcode 230: Kth Smallest Element in a BST

Nov. 6, 2017

Introduction

It is the hard level algorithm called Kth smallest element in BST. When k value is one, the problem can be called to find largest smaller element in a binary search tree given the number.

It is very good discussion with the peer how to write an iterative solution. I did write down the code using C# and then I have to figure out how to get good rating from the peer.

Here is the C# practice code. I added main function after the mock interview.

Code review 


Here is the evaluation I got. I need to learn how to work with the peer, and follow the hint better.



Follow up 


Nov. 7, 2017
I found a bug in my code, the null pointer exception on line 35:
while(currentNode.right.key < num)


Here is the fix, C# code is here. currentNode.right == null is added to line 41. ( * bug fix No. 1*)

Nov. 10, 2017 11:44 PM

I finally figured out the thing I did wrong in my last mock interview. The code I wrote in Nov. 6 is wrong, and also the fix of bug on Nov. 7 ( * bug fix No. 1*) is also wrong. I finally understood that I was too stubborn and did not take the advice in mock interview.


Also the above code will not work for the following binary search tree:
Given the value 11, largest smaller BST key's value should be 10, but the solution will return 8 instead. Also the above code has null pointer run time exception on line 36, currentNode's right child may be null pointer, need to put a guard clause to check currentNode.right != null.


Nov. 10, 2017
11:19 PM
I had 10:00 pm mock interview, the peer worked on the algorithm. I had chance to find my problem based on the following test case. Great thanks for the peer, who is very patient, and think about the test case carefully.

Given number 11, the largest smaller BST key is 10. How to find node with value 10?   
First, start from root node with value 19, 19 is bigger than 10, so go to its left child. Left child value is 8 and it is smaller than 11, then set the value to look for (denote as LargestValue) as 8. And go to its right child to search. The node's value is 11 which is not smaller than 11, then go to left child 10, and set LargestValue = 10. Node 10 is leaf node without any child. 10 is the answer. 

In other words, find smaller one, go right; find bigger one, then go left. Until the traverse reaches the leaf node. Left, right, left. 

No comments:

Post a Comment