Dsa
Binary Search Tree
Medium
The Path Pivot Count
You are navigating a BST where each node represents a junction. A 'Pivot' occurs when your path from node A to node B changes direction (e.g., from a Left-child link to a Right-child link, or vice versa). Build a BST from the given sequence (first element as root). Given two values X and Y present in the tree, calculate the total number of pivots on the unique path between them.
Input Format:
- Line 1: A space-separated list of integers to build the BST.
- Line 2: Two integers X and Y.
Output Format:
- A single integer representing the count of direction changes (pivots).
Example:
Input:
10 5 15 3 7 12 18
3 12
Output:
2
Explanation: Path is 3 -> 5 -> 10 -> 15 -> 12. Directions: 3-5 (Right), 5-10 (Right), 10-15 (Right), 15-12 (Left). One pivot at node 15. Wait, path is 3-5 (Up-Right), 5-10 (Up-Right), 10-15 (Down-Right), 15-12 (Down-Left). Pivots occur at the LCA (10) and at node 15.
Key concepts
binary_search_treelowest_common_ancestortree_traversal
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