Path In Zigzag Labelled Binary Tree - Problem

In an infinite binary tree where every node has two children, the nodes are labelled in row order with a zigzag pattern.

In the odd numbered rows (1st, 3rd, 5th, ...), the labelling is left to right.

In the even numbered rows (2nd, 4th, 6th, ...), the labelling is right to left.

Given the label of a node in this tree, return the labels in the path from the root of the tree to the node with that label.

Input & Output

Example 1 — Target in Level 4
$ Input: label = 14
Output: [1,3,4,14]
💡 Note: Node 14 is in level 4 (even level, right to left). Working backwards: 14 → parent 4 (level 3) → parent 3 (level 2) → parent 1 (root)
Example 2 — Target in Level 3
$ Input: label = 26
Output: [1,2,6,26]
💡 Note: Node 26 is in level 5 (odd level, left to right). Path: 26 → parent 6 (level 4) → parent 2 (level 2) → parent 1 (root)
Example 3 — Root Node
$ Input: label = 1
Output: [1]
💡 Note: Root node has no parents, so path contains only itself

Constraints

  • 1 ≤ label ≤ 106

Visualization

Tap to expand
Path In Zigzag Labelled Binary Tree INPUT Zigzag Labelled Binary Tree 1 Row 1 2 3 Row 2 4 5 6 7 Row 3 8 14 Row 4 (R to L) Target: 14 Path nodes label = 14 ALGORITHM STEPS 1 Find Row Level Row where 2^(r-1) <= 14 < 2^r Row 4: 8 <= 14 < 16 2 Build Path Upward Start with label, find parent path = [14] 3 Zigzag Correction Mirror label for even rows: mirror = start + end - label Row 4: mirror(14)=8+15-14=9 parent(9)=9/2=4 [Row 3] Row 3: mirror(4)=4+7-4=7 parent(7)=7/2=3 [Row 2] parent(3)=3/2=1 [Row 1] 4 Reverse Path [14,4,3,1] --> [1,3,4,14] FINAL RESULT Path from root to 14: 1 3 4 14 [1,3,4,14] OK - Path Found! Key Insight: In a zigzag tree, even-row labels are reversed. To find the correct parent, mirror the label first: mirrored_label = (2^(row-1)) + (2^row - 1) - current_label, then parent = mirrored_label / 2 This converts zigzag positions to normal binary tree positions for parent calculation. Time: O(log n) TutorialsPoint - Path In Zigzag Labelled Binary Tree | Optimal Solution
Asked in
Facebook 15 Microsoft 12 Amazon 8
23.2K Views
Medium Frequency
~15 min Avg. Time
892 Likes
Ln 1, Col 1
Smart Actions
💡 Explanation
AI Ready
💡 Suggestion Tab to accept Esc to dismiss
// Output will appear here after running code
Code Editor Closed
Click the red button to reopen