Path in ZigZag Labelled Binary Tree
Tags: computerscience, 100daysofcode, java
Published: 2021-02-16 01:22:46

Every so often when I am practicing algorithm problems, I run into a problem that requires a bit of math to solve. For this “Path in ZigZag Labelled Binary Tree” problem, my initial impression was that I would have to do a breadth-first search on a tree. As I quickly found out, I was not dealing with a typical tree problem. This problem requires a bit of math to solve. I don’t know about you, but my math is a bit rusty.

## The Problem

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

In the odd numbered rows (ie., the first, third, fifth,…), the labelling is left to right, while in the even numbered rows (second, fourth, sixth,…), 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.

## Example

**Example 1:**
**Input:** label = 14
**Output:** [1, 3, 4, 14]

**Example 2:**
**Input:** label = 26
**Output:** [1, 2, 6, 10, 26]

[Link to Problem](https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/)

![ZigZag Tree](https://cdn-images-1.medium.com/max/2718/1*JO4V_8UVNLxTMRvdMYr82g.png)<center>*ZigZag Tree*</center>

![Normal Tree](https://cdn-images-1.medium.com/max/2694/1*ZBFBXHl6_6lL2YLzCiVPGw.png)<center>*Normal Tree*</center>

## Some Math

As promised there is going to be some math. I just want to go over some concepts to make sure that we are on the same page.

First off, here is a post about [tree basics](https://www.danielleskosky.com/i-speak-for-the-trees/). In this problem we are dealing with a [full and complete binary tree](https://en.wikipedia.org/wiki/Binary_tree). This is also known as a **perfect** binary tree. For a perfect binary tree, each level has exactly twice as many nodes as the previous level.

Let’s refresh our memories on logarithms a bit. I found two great resources to help us do that. Here [is one](https://medium.com/@venk_3193/logarithms-and-binary-trees-3c610641310c) by VC that is pretty good and here [is one](https://medium.com/basecs/looking-for-the-logic-behind-logarithms-9e79d7666dda) by Vaidehi Joshi that is pretty good as well. I like some things that VC says:
> # *“Log of a number is the number of times you need to divide that number by the ‘base’ to get an output equal to 1.”*

I like how VC explains it in terms that us simple folk can understand. Let’s look at some examples.

* log2(8) = 3. Divide 8 by 2 (the base). Do it 3 times and you get 1.

* Log10(10000) = 4. Divide 10000 by 10 (the base). Do it 4 times and you get 1.

Ok, so that’s not so bad. Now let’s see how this can be applied to the perfect binary tree in the problem. First take a look at the figure below to see how we are going to refer to the depths of of the levels for the binary tree in this problem.

![](https://cdn-images-1.medium.com/max/2788/0*_0OmfAK50Qv7qZW8.png)

For starters, let’s see how we can find both the fist and last node in a level for a particular depth.

![](https://cdn-images-1.medium.com/max/2000/0*urbL04uI9nSEYv_0.png)

Let’s see how this can be applied to depth = 3.

![](https://cdn-images-1.medium.com/max/2000/0*-YybhS7MkpFV18zf.png)

Here is a neat trick. Let’s see if we can find how many nodes are contained up until a certain depth.

![](https://cdn-images-1.medium.com/max/2000/0*N7iCHobKKeUS1YVg.png)

Now let’s see how for a particular node number, we are able to find the depth that the node is located.

![](https://cdn-images-1.medium.com/max/2000/0*Riw8oqHELdCp_DX3.png)

The example for finding the depth from a node number uses numbers that have 2 as a root. Let’s look at when this isn’t the case.

* log2(10) = 3.32 ~ 3

* log2(13) = 3.70 ~ 3

As you can see, although node 10 and node 13 come out to decimal, they still have a depth of 3. So, when we are finding depth based off a node number, we will floor the result.

Well, I think we have just about the covered the basics. Let’s start figuring out how to solve the problem.

## Brute Force

This problem is essentially asking us to return a list that has the path from a node to the root.

![Node to Root](https://cdn-images-1.medium.com/max/2724/1*zK1aXwtXUzRECDo5eJZTow.png)<center>*Node to Root*</center>

When I tried to solve the problem, I first built a tree that contained nodes for all the values up until the “label” that is given as input. I didn’t actually build a tree though. I instead used nested lists to represent each level of the tree. The lists followed the zigzag pattern.

What I realized is that if you take the node that corresponds to the label given as input then you can can assign an index value to that node. Then take that index value and divide by two. This will give the index value of the parent node. In the example below, I used label = 10 to make it more interesting.

![](https://cdn-images-1.medium.com/max/2670/0*SmQ3VnaBBSZRYwgy.png)

Something to note is that if the tree was not in a zigzag pattern and was a “normal tree”, then the node values could be divided by two to get the value of the parent node. Go up to the “Normal Tree” picture above and try it. Just make sure to floor the result.

Here is the code for the brute force approach that I took:

{% gist
https://gist.github.com/djl218/9ef1803c3571e22e9eba648a9468bc2f %}

Pretty good approach in my opinion. Just not quite fast enough for the big leagues. The time complexity of this algorithm is O(n + logn) with n = label. The space complexity is O(n + logn) as well.

## Optimal Solution

Here is some real top-notch code submitted by LeetCode user @alok5. You can find the original post [here](https://leetcode.com/problems/path-in-zigzag-labelled-binary-tree/discuss/323312/Simple-solution-in-java-(Using-properties-of-complete-binary-tree)-(O-log-N)).

{% gist
https://gist.github.com/djl218/4234452e1e3e663133e7ae574bffbae5 %}

The basic idea behind the algorithm is fairly straightforward.

1. Add the node to the back of the result list.

1. Find the depth of the node.

1. Find the parent of the node.

1. Repeat steps with the parent as the new node.

When using Math.log() in Java, it defaults to base 10. In the algorithm Math.log(parent) / Math.log(2) is how to change the base to two. Read more about that [here](https://www.khanacademy.org/math/algebra2/x2ec2f6f830c9fb89:logs/x2ec2f6f830c9fb89:change-of-base/a/logarithm-change-of-base-rule-intro).

## Some Illustrations

Let’s take a look at some illustrations to really give us a crystal clear mental picture of what is happening with this algorithm.

![parent = 14](https://cdn-images-1.medium.com/max/2000/1*GpESNA5bDy6fchkhH3sq4g.png)<center>*parent = 14*</center>

![parent = 14](https://cdn-images-1.medium.com/max/2668/1*MuortbQ-1NUNF_W1yS2SFg.png)<center>*parent = 14*</center>

Ok, so I know what you are thinking. This tree does not follow the zigzag pattern that is described in the problem. In fact it is a pretty normal-looking full and complete binary tree with the exception of the last level. The last level is reversed.

That’s right. Only the last level is reversed. This is the level that contains the “label”. Label or the “parent” is shaded red. The other nodes in this level are shaded blue. This blue-shaded level is the only level that is reversed.

Why is only this level reversed?

Go back up to the “Normal Tree” picture. The parent of the node 14 is 7. However, in the zigzag tree the parent of node 14 is 4. To find the parent in the zigzag tree, think of it like this.

Pretend we are actually dealing with a normal tree. To find the “zigzag” parent in a normal tree we can do one of two things:

1. We can reverse the current level. Now the parent of the node in the reversed level is the desired “zigzag parent”.

1. We can reverse the level above. Now the parent of the label node is the desired “zigzag parent”.

That is what offset is doing. If you remember from above, 2^(depth + 1) — 1 is the last node for a particular level. Last node — parent = distance that parent is from end of the level = offset.

Remember that the first node = 2^(depth). So then take the offset value (1) and add it to the first node in the level (8) and divide this value by 2. 
(8 + 1) / 2 = 9 / 2 = 4. **In a normal tree, the parent of node 9 is 4.**

So really we are finding the parent of node 9 in a normal tree. Node 9 is like the mirror node for 14. **Offset is like finding the mirror value for a node.**

![parent = 4](https://cdn-images-1.medium.com/max/2000/1*HgRY3uwHyyJjpclBQjKwpA.png)<center>*parent = 4*</center>

![parent = 4](https://cdn-images-1.medium.com/max/2672/1*slXNbOqVhOyYL428Lt2FVA.png)<center>*parent = 4*</center>

The same thing happens when parent = 4. The offset is 3. So 7 is like the mirror value for 4. So, when this level gets reversed, 4 goes in the place where 7 was. 3 is the “zigzag parent” of 4.

![parent = 3](https://cdn-images-1.medium.com/max/2000/1*cVsHJn21x2ZBiYzB-4pU_A.png)<center>*parent = 3*</center>

![parent = 3](https://cdn-images-1.medium.com/max/2688/1*5ioWG8wGtC9jaqbcf5vCMg.png)<center>*parent = 3*</center>

Same thing happens again, but there is only the root node left, so it doesn’t matter so much. Also notice that parent = 1. This terminates the while loop and the result is returned

```code
result = [1, 3, 4, 14]
```

## Time Complexity

The time complexity for this algorithm is O(logn) with n = label.

## Space Complexity

The space complexity of this algorithm is O(logn) as well.

Learn some more [Big-O tips and tricks](https://www.danielleskosky.com/big-o/).

## Get Better at Algorithms!

Algorithms and data structures are pretty tough. They are definitely taking a while for me to get the hang of them. However, there are some great resources out there, and I feel obligated to share some that have been most helpful to me. If I missed any that have been helpful to you, be sure to mention them in the comments.

* **Cracking the Coding Interview** — Great resource. Really gets you in the right mindset for interviews. You can find it [here](https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850).

* **Elements of Programming Interviews** — Another great book. Personally, I like this one more than CTCI, but YMMV. You can find it [here](https://www.amazon.com/Elements-Programming-Interviews-Java-Insiders/dp/1517671272/ref=pd_lpo_14_t_0/134-2745636-3821839?_encoding=UTF8&pd_rd_i=1517671272&pd_rd_r=4eebd030-1368-436b-9bdd-22a403a57eae&pd_rd_w=ku4HH&pd_rd_wg=qY5q5&pf_rd_p=7b36d496-f366-4631-94d3-61b87b52511b&pf_rd_r=Y44KR67YH071M3P9JGSH&psc=1&refRID=Y44KR67YH071M3P9JGSH).

* **Grokking the Coding Interview** — Can’t emphasize this one enough. Haven’t seen it mentioned it too often. Explains patterns that occur in different coding challenge problems. Great at providing a big-picture of all the different algorithm problems you might encounter. Check it out [here](https://www.educative.io/courses/grokking-the-coding-interview).

* **Grokking Dynamic Programming** — Dynamic programming is tough. [This course](https://www.educative.io/courses/grokking-dynamic-programming-patterns-for-coding-interviews) has definitely helped me get a better understanding.

* **Tushar** **Roy** — Tushar really knows his stuff. His dynamic programming playlist is especially good. Check out his awesome [YouTube channel](https://www.youtube.com/user/tusharroy2525/featured).

* **Back To Back SWE** — Great [YouTube Channel](https://www.youtube.com/channel/UCmJz2DV1a3yfgrR7GqRtUUA). Highly recommend.

* **Kevin Naughton Jr.** — Another awesome [YouTube channel](https://www.youtube.com/channel/UCKvwPt6BifPP54yzH99ff1g). Great at going over problems and gives helpful advice.

* **Base CS** — Vaidehi Joshi does a great job of laying out the fundamentals of algorithms and data structures. Check out the blog series [here](https://medium.com/basecs). She also has a [podcast](https://www.codenewbie.org/basecs) that I give two thumbs up.

* **Coding Challenge Website** — There are plenty of different ones to choose from. [HackerRank](https://www.hackerrank.com/), [CodeWars](https://www.codewars.com/), and [Edabit](https://edabit.com/) all seem to be pretty popular. I personally use [LeetCode](https://leetcode.com/). Find the one that works for you!

* **Pramp** — Do mock interviews! The sooner the better! [Pramp](https://www.pramp.com/) has been a huge help to me.

Well, I hope that was useful. Thanks for reading my post and best of luck with your learning about data structures and algorithms!