Dsa
Binary Search Tree
Medium
Genetic Level-Links
Two nodes in a BST are 'Genetically Linked' if they are at the same depth (distance from root) and the absolute difference between their values is less than or equal to K. Build a BST from a sequence and count how many unique pairs of Genetically Linked nodes exist.
Input Format:
- Line 1: Space-separated integers for the BST.
- Line 2: The integer K.
Output Format:
- Total count of pairs.
Example:
Input:
10 5 15 2 7 12 18
6
Output:
2
Explanation: Depth 1: (5, 15) diff 10. Depth 2: (2,7) diff 5, (7,12) diff 5, (12,18) diff 6, (2,12) diff 10, (7,18) diff 11, (2,18) diff 16. Linked pairs: (2,7) and (7,12). Total 2.
Key concepts
binary_search_treelevel_order_traversalsearch
Practise this out loud — free
Start a mock interview on THIS exact question — a voice AI interviewer opens with it, pushes back like a real onsite, then hands you an instant scorecard.
🎙 Practise this question now