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
Zigzag Labelled Binary Tree - Find Path to Node 141Level 1 (L→R)32Level 2 (R→L)4567Level 3 (L→R)15141312Level 4 (R→L)Path to Node 14:1. Start at root: 12. Go to left child: 33. Go to left child: 44. Go to right child: 14Result: [1, 3, 4, 14]Zigzag Pattern: Level 1 (L→R), Level 2 (R→L), Level 3 (L→R), Level 4 (R→L)...Algorithm: Use math to calculate parent relationships without building treeTime: O(log n) | Space: O(log n)
Understanding the Visualization
1
Zigzag Tree Structure
Infinite binary tree with alternating left-right, right-left labeling per level
2
Find Target Node
Locate the target node in the appropriate level
3
Trace Path
Work backwards from target to root using parent relationships
Key Takeaway
🎯 Key Insight: Each level has predictable zigzag pattern allowing direct mathematical calculation of parent-child relationships
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