Logo
IconChallenge
Icon
IconProblem
IconSolutions
IconSubmissions

Path In Zigzag Labelled Binary Tree

XPChallenge Points: 20
levelLevel: Medium

In an infinite binary tree, rows are labeled alternately:

  • Odd-numbered rows (1st, 3rd, …) are labeled left → right.

  • Even-numbered rows (2nd, 4th, …) are labeled right → left.

Given a node label, return the path of labels from the root (1) to that node.

Idea:
Let row index be 0-based (row 0 has label range [1,1], row 1 is [2,3], row 2 is [4,7], …).
For a node at row r with zigzag label label:

  1. Convert to its normal (left→right) index within the row:

    start = 2^r, end = 2^(r+1) - 1 idx = label if r is even = start + end - label if r is odd
  2. Parent’s normal index is idx // 2, which lies on row r-1.

  3. Convert that parent normal index back to the zigzag label of row r-1:

    prevStart = 2^(r-1), prevEnd = 2^r - 1 parent_label = parent_index if (r-1) is even = prevStart + prevEnd - parent_index if (r-1) is odd

Repeat until reaching label 1. Reverse the collected list for root→node order.

Example 1:

Input: label = 14

Output: [1, 3, 4, 14]

Example 2:

Input: label = 26

Output: [1, 2, 6, 10, 26]

Example 3:

Input: label = 1

Output: [1]

to Continue
like
dislike

Accepted:

Submission:

IconReport an issue
Icon
IconCode
IconYou need toto run or submitYou need toto run or submit
IconTest Case
IconTest Result