Problem 1104

Abstract / Summary

Find the path from the root to a given node in a zigzag labelled binary tree.

Note

The full problem description, including helpful examples, can be found on LeetCode.

Python 1104.py

class Solution:
    def pathInZigZagTree(self, label: int) -> List[int]:
        result = [ label ]
        if label == 1:
            return result

        # compute highest and lowest value for each row
        high = low = row = 1
        rows = [ [ 1, 1 ] ] # first row
        while high < label:
            high = 2 * high + 1
            low  = 2 * low
            rows.append ([ low, high ])

        # process rows bottom-up
        while label > 1:
            low, high = rows.pop()
            l2, h2    = rows[-1]      # peek to level above

            if len(rows) & 1:
                pos   = label - low   # left-to-right
                label = h2 - pos // 2 # right-to-left
            else:
                pos   = high - label  # right-to-left
                label = l2 + pos // 2 # left-to-right

            result.append(label)

        return reversed(result) # restore original order
29 lines | 942 bytes | submitted February 29, 2024 | GitHub   40% comment ratio | tab size 4 | low complexity

Difficulty

This problem is ranked as
easy medium hard

and has an acceptance rate of about 76% (60k+ submissions).

Typical patterns to solve this problem:
  • Binary Tree
  • Math
  • Tree
I solved 663 easy, 1250 medium and 309 hard problems

AI Disclaimer

Every single line of code was written by me, 100% from scratch, between August 2023 and August 2024.
However, two years later I set up this website and used various AI tools to generate most of the walkthrough / explanations below.

See this dedicated page for more details.
LeetCode profile | GitHub repo

Code Walkthrough

Overview

The provided implementation computes the path from a given node label to the root in a binary tree whose rows are alternately ordered left-to-right and right-to-left (a “zig-zag” tree). The algorithm builds a compact representation of each tree level, then walks upward from the target node, translating positions between the two ordering directions until the root is reached. The final path is returned in root-to-node order.

Key Steps

Initialisation and early exit

result = [ label ]
if label == 1:
    return result

The method starts by placing the target label in the result list. When the label is the root (value 1) the function returns immediately, handling the minimal input case without further work.

Building row boundaries

high = low = row = 1
rows = [ [ 1, 1 ] ]          # first row
while high < label:
    high = 2 * high + 1
    low  = 2 * low
    rows.append ([ low, high ])

This loop constructs a list rows where each element is a two-element list [low, high] describing the smallest and largest label in a tree row. The first row is [1,1]. For each subsequent row the lowest label doubles (the leftmost node of a perfect binary tree) and the highest label follows the pattern 2*high+1. The loop stops once the highest label of the current row meets or exceeds the target label, guaranteeing that the target resides in the last stored row. By pre-computing these boundaries the algorithm avoids repeated calculations during the upward traversal.

Bottom-up traversal of rows

while label > 1:
    low, high = rows.pop()
    l2, h2    = rows[-1]      # peek to level above

    if len(rows) & 1:
        pos   = label - low   # left-to-right
        label = h2 - pos // 2 # right-to-left
    else:
        pos   = high - label  # right-to-left
        label = l2 + pos // 2 # left-to-right

    result.append(label)

The loop iteratively moves the current label upward until it reaches the root. Each iteration removes the current row’s boundaries from rows and looks at the next higher row (rows[-1]). The parity of the remaining rows (len(rows) & 1) determines whether the current row is ordered left-to-right (odd depth) or right-to-left (even depth).

When the row is left-to-right, the position of label within the row is label - low. The parent’s label in the opposite-ordered row is computed by subtracting half of that position from the upper row’s high bound (h2 - pos // 2).

When the row is right-to-left, the position is high - label. The parent’s label in the left-to-right row is obtained by adding half of that position to the upper row’s low bound (l2 + pos // 2).

The computed parent label is appended to result. This arithmetic translation replaces the need for explicit tree navigation, keeping the traversal tight and deterministic.

Restoring root-to-node order

return reversed(result) # restore original order

During the upward walk the labels are collected from leaf to root. Returning reversed(result) yields the required root-to-node ordering without an extra copy, leveraging Python’s iterator protocol.

Edge Cases Handled

The early return for label == 1 covers the smallest possible tree where the path consists of a single node.

The while-loop that builds rows uses a condition high < label, ensuring that even when label is exactly the highest value of a row, that row is still recorded, so the subsequent pop operation always finds a matching row.

The parity check (len(rows) & 1) correctly distinguishes the ordering direction for every depth, including the deepest row that may contain a single node (the case when label is a power of two).

Integer division (// 2) guarantees that parent computation works for both even and odd positions, handling the fact that each parent has exactly two children in a perfect binary tree.

Performance Optimizations

The algorithm avoids constructing an explicit tree structure; it works solely with numeric boundaries, which reduces memory usage to a list of row intervals whose length is proportional to the tree height.

Row boundaries are generated in a single forward pass, and the upward traversal reuses these pre-computed values, eliminating repeated exponentiation or logarithmic calculations.

Parent calculation uses only a few arithmetic operations per level, and the use of pop and direct indexing (rows[-1]) provides O(1) access to the needed row data.

Returning a reversed iterator instead of building a new list prevents an additional linear-time copy, keeping the overall work linear in the number of rows visited.

written by openai gpt

ELI5 - Simplified Explanation

Imagine a tall tower made of blocks where the numbers are written in a special pattern. In the first row you have a one. In the second row the numbers go from two to three, but they are written backward. In the third row the numbers go from four to seven, and they are written from left to right. Every time a new row starts, the numbers flip their direction like a snake slithering back and forth.

The goal is to find the secret path from a specific number at the bottom all the way back up to the top. To do this, the code first figures out which row the number lives in by doubling the numbers and adding one. It keeps track of the start and end of every row so it knows where everything belongs.

Once the location is found, the code starts walking backward toward the top. It looks at the number and figures out its mirror image in the row above it. Because the rows swap directions, the math has to flip too. If the current row is going left to right, the math for the row above accounts for it being right to left. By shrinking the number and jumping to the parent row step by step, the code collects every stop along the way. Finally, since the path was built starting from the bottom, the collection is turned around to show the journey from the very top down to the starting number.

written by google gemini

Code Quality

Several LLMs ranked my code quality on a scale from 1 (very poor) to 10 (outstanding):
n = 27 | median = 6 | μ = 6.04 | σ = 1.60

Complexity Analysis

Time: logarithmic
As a rule of thumb, the maximum input size for one second execution time is
  • factorial: up to 10 elements
  • exponential: up to 20 elements
  • polynomial: a few thousand elements
  • loglinear: up to 100,000 elements
  • linear: a few million elements
  • logarithmic: a billion elements
  • constant: practically unlimited
generated automatically

Other Solutions

I wrote a basic crawler to find other solutions to that problem.
Obviously, I did that after I solved the problem myself.

In general, AlgoMonster and WalkCCC solutions are high-quality and always worth a look.
I haven't checked most of the other solutions, but they might be helpful as well.

And of course, the LeetCode forum is always a good place (or even the best) to look for alternative approaches.

(click on a column header to sort the table)
author
author solutions
www AlgoMonster C++ Java Python TS
WalkCCC C++ Java Python
leetcode.ca C++ Java Python Go
Progiez C++ Java Python
github BigEggStudy C#
black-shadows C++
charles-wangkai Java
everthis JS
fsq C++
halfrost Go
JoshCrozier JS
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
AlgoMonster C++, Python, Java, TypeScript
WalkCCC C++, Python, Java
leetcode.ca C++, Go, Java, Python
Progiez C++, Java, Python
BigEggStudy C#
black-shadows C++, C++
charles-wangkai Java
everthis JavaScript
fsq C++
halfrost Go
JoshCrozier JavaScript
keineahnung2345 C++
lkwq007 Python
lzl124631x C++
suxrobGM C#
varunu28 Java
wisdompeak C++
27 links | 17 authors | 7 languages

Videos

4 videos   did my crawler come up with invalid videos ? drop me a line.

Similar Problems

1 similar problem

Solved On The Same Day

4 solutions   February 29, 2024

Extra

There are a few extra pages giving you some insights into my setup:
  • Tech Stack - my development environment and tools
  • AI - how AI helped me create this website (NOT solving the problems)
  • Progress - progression over time
  • Quality - code quality