Given a BST and an integer. Find the least absolute difference between any node value of the BST and the given integer.
Input Format:
The values in the string are in the order of level order traversal of the tree where, numbers denote node values, and a character “N” denotes NULL child.
For example:
For the above tree, the string will be: 1 2 3 N N 4 6 N 5 N N 7 N
Example 1:
Input:
S = 10 2 11 1 5 N N N N 3 6 N 4
K = 13
Output: 2
Explanation: K=13. The node that has
value nearest to K is 11. so the answer
is 2
Example 2:
Input:
S = 8 1 9 N 4 N 10 3
K = 9
Output: 0
Explanation: K=9. The node that has
value nearest to K is 9. so the answer
is 0.
Your Task:
You don't need to read input or print anything. Your task is to complete the function minDiff() that takes the root of the BST and an integer K as its input and returns the minimum absolute difference between any node value of the BST and the integer K.
Expected Time Complexity: O(Height of the BST).
Expected Auxiliary Space: O(Height of the BST).
Constraints:
1 <= N <= 100000
If you have purchased any course from GeeksforGeeks then please ask your doubt on course discussion forum. You will get quick replies from GFG Moderators there.
saiujwal13083 | 269 |
ppsvikhyat17 | 268 |
reclone_rk | 220 |
vt9941 | 216 |
bikramjs97 | 212 |
saiujwal13083 | 528 |
ppsvikhyat17 | 456 |
generic_coder | 424 |
vt9941 | 340 |
SourabhPatel | 328 |
blackshadows | 5448 |
Ibrahim Nash | 5438 |
akhayrutdinov | 5111 |
mb1973 | 4976 |
Quandray | 4752 |