Path In Zigzag Labelled Binary Tree - Problem
Imagine a special infinite binary tree where nodes are labeled in a unique zigzag pattern! π²
Here's how the labeling works:
- Odd-numbered rows (1st, 3rd, 5th...): Labels go left to right β β β
- Even-numbered rows (2nd, 4th, 6th...): Labels go right to left β β β
For example:
1 (Row 1: leftβright)
/ \
3 2 (Row 2: rightβleft)
/ \ / \
4 5 6 7 (Row 3: leftβright)
Your mission: Given a node's label, find the complete path from the root (node 1) to that node!
Input: An integer label representing a node in the zigzag binary tree
Output: An array containing all labels in the path from root to the target node
Input & Output
example_1.py β Basic Path Finding
$
Input:
label = 14
βΊ
Output:
[1, 3, 6, 14]
π‘ Note:
Node 14 is in level 4. Tracing back: 14 β 6 (level 3) β 3 (level 2) β 1 (level 1, root). The complete path from root to node 14 is [1, 3, 6, 14].
example_2.py β Early Level Node
$
Input:
label = 26
βΊ
Output:
[1, 2, 6, 10, 26]
π‘ Note:
Node 26 is in level 5. Working backwards through the zigzag pattern: 26 β 10 β 6 β 2 β 1, giving us the root-to-target path [1, 2, 6, 10, 26].
example_3.py β Root Node Edge Case
$
Input:
label = 1
βΊ
Output:
[1]
π‘ Note:
The root node 1 has no parent, so the path is simply [1]. This is the simplest case where the target is the root itself.
Constraints
- 1 β€ label β€ 106
- The given label will always exist in the zigzag binary tree
- Tree property: Every node has exactly two children (except leaf nodes)
Visualization
Tap to expand
Understanding the Visualization
1
Identify the Level
First, determine which level (floor) contains our target node using powers of 2
2
Convert to Normal Position
Transform the zigzag position to what it would be in a normal left-to-right binary tree
3
Find the Parent
In a normal binary tree, parent is at position divided by 2 in the previous level
4
Convert Back to Zigzag
Transform the parent's normal position back to its actual zigzag position
5
Repeat Until Root
Continue this process until we reach the root node (level 1)
Key Takeaway
π― Key Insight: By understanding the mathematical relationship between zigzag positions and normal binary tree positions, we can calculate any path in O(log n) time without building the tree!
π‘
Explanation
AI Ready
π‘ Suggestion
Tab
to accept
Esc
to dismiss
// Output will appear here after running code