How To Find All 3-Digit Numbers In A Binary Tree

This is an exercise I failed to solve in a past interview a long time ago, in a galaxy far, far away. I ran out of time and didn’t finish it.

Off the top of my head, the exercise was something like this:

Find all 3-digit numbers you can create by visiting a binary tree. To create a 3-digit number, given a node, visit either the left or right subtree, and concatenate the value you find in three nodes.

The next tree has 4 3-digit numbers.

        1
       / \
      /   \
     2     7
    / \   /
   5   9 4
  /
 3

They are 125, 129, 253, and 174. No, 127 is not a valid number here. We should visit one subtree at a time.

To finally close the open-loop in my mind, here’s my solution.

Let’s solve the simplest scenario first

If we have a tree with only the root node and the left subtree only with leaves, we could write a function to “walk” that simple tree like this,

List<int> Walk(int root, Tree subTree)
{
    if (subTree == null) return [];

    var candidate = root * 100 + subTree.Value * 10;

    List<int> result = [];
    if (subTree.Left != null) result.Add(candidate + subTree.Left.Value);
    if (subTree.Right != null) result.Add(candidate + subTree.Right.Value);
    return result;
}

Here root is the value of the root node and subTree is either the left or right subtree of our root node.

If we call Walk() with our example tree,

        1
       / .
      /   .
     2     .
    / \   .
   5   9 .

The root is 1, the node in the left subtree is 2, and the node in the left subtree again is 5, then the 3-digit number is calculated as 1*100 + 2*10 + 5.

Walk() passing only the root node and the left subtree of our sample tree returns,

//        1
//       / .
//      /   .
//     2     .
//    / \   .
//   5   9 .

Walk(1, new Tree(2,
            new Tree(5, null, null),
            new Tree(6, null, null)));
// List<int>(2) { 125, 129 }

That will only work for a simple tree.

Let’s cover more complex trees

With Walk(), we only find numbers by visiting one node in a simple tree, so let’s use recursion to visit all other nodes.

Here’s a recursive function Digits() that uses Walk(),

List<int> Digits(Tree aTree)
{
    if (aTree == null) return [];
	
    return Walk(aTree.Value, aTree.Left)
           // ^^^
           // We visit the left subtree from the root
              .Concat(Walk(aTree.Value, aTree.Right))
              //      ^^^^
              // We visit the right subtree from the root
			  
              .Concat(Digits(aTree.Left))
              //      ^^^^^
              // Find digits on the left subtree
              .Concat(Digits(aTree.Right))
              //      ^^^^^
              // Find digits on the right subtree
              .ToList();
}

Digits() starts visiting the left and right subtrees from the root node. Then, it recursively calls itself for the left and right subtrees and concatenates all the intermediary lists.

All the pieces in one single place

Here’s my complete solution,

record Tree(int Value, Tree Left, Tree Right);

List<int> Walk(int root, Tree subTree)
{
    if (subTree == null) return [];

    var candidate = root * 100 + subTree.Value * 10;

    List<int> result = [];
    if (subTree.Left != null) result.Add(candidate + subTree.Left.Value);
    if (subTree.Right != null) result.Add(candidate + subTree.Right.Value);
    return result;
}

List<int> Digits(Tree aTree)
{
    if (aTree == null) return [];
	
    return Walk(aTree.Value, aTree.Left)
              .Concat(Walk(aTree.Value, aTree.Right))
			  
              .Concat(Digits(aTree.Left))
              .Concat(Digits(aTree.Right))
              .ToList();
}

var tree1 =
    new Tree(1,
        new Tree(2,
            new Tree(5,
                new Tree(3, null, null),
                null),
            new Tree(9, null, null)),
        new Tree(7,
            new Tree(4, null, null),
            null));
Digits(tree1)
// List<int>(4) { 125, 129, 174, 253 }

Et voilà!

I know it’s too late. Months have passed since then, but I wanted to solve it anyway. Don’t ask me what company asked me to solve that. I can’t remember. Wink, wink!

For other interviewing exercises, check how to evaluate a postfix expression, how to solve the two-sum problem, and how to shift the elements of an array.

Sell Something or Be Ready to Sell Your Time

Selling feels dirty to far too many people.

Maybe that’s because we have the wrong impression of selling as tricking people into buying something they don’t need with pushy lines or sales tactics. “I’m making an exception for you. Hurry up! If my boss finds out about this, I’m fired.”

The truth is we’re selling all the time, even without realizing it.

Isra Bravo, the best copywriter of Spain, taught me that we’ve been selling since we’re kids. We sell ourselves to get our parents’ attention. And as adults, we continue selling: when looking for a job or for a romantic partner.

The other day, a salesy DM made me change my perspective on selling: from pushy sales tactics to genuine help.

If we aren’t ashamed of helping, we shouldn’t be afraid of selling.

These days, jobs are uncertain and layoffs are always around the corner. Either you sell something (a book, course, template, coaching) and free yourself, or you sell 8 hours or more of your time and become a slave.

Remember, “whoever sits in a cubicle is replaceable.” (Choose Yourself by James Altucher) Sell something or sell your time forever.

Put Blood in Your Opening Lines and Keep Your Readers Hooked Forever

People have short attention spans, and shorter for boring things.

That’s why our job as writers is to keep readers moving from the first sentence to the next and to the next…

I learned from James Altucher, one of my favorite writers, to study the opening lines of the books I read to write my own.

Following that advice, here are some of my favorite opening lines:

Genesis by Moses

In the beginning, God created the heavens and the earth.

That’s the opening line of the Bible, Genesis 1:1. It doesn’t matter if you believe it or not, those 10 words hook you right from the start.

If you read it for the first time and with fresh eyes, you can’t avoid asking:

  • Who is this God?
  • “In the beginning”…Was there anything before?
  • How did He do that?
  • And more important, why?

We’ve been trying to answer that for years.

One Hundred Years of Solitude by Gabriel García Márquez

Many years later, as he faced the firing squad, Colonel Aureliano Buendía was to remember that distant afternoon when his father took him to discover ice.

I didn’t read One Hundred Years of Solitude until the end. Sorry!

That’s one of the required books in my Spanish classes. I was too young. Too many members of the Buendía family that I got lost.

Even though I didn’t read it until the end, for some reason, I memorized that opening line in Spanish, its original language. It’s way stronger and more memorable in Spanish.

“Many years later,” so it doesn’t start right at the beginning.

“The firing squad,” what did this colonel do?

Before getting shot, of all things, he remembers his father taking him to discover ice? Wait! Was ice that new? When is this happening?

Choose Yourself by James Altucher

I was going to die.

Five words that hook you. You can’t avoid asking how and why.

To add more drama, he continues:

I was going to die. The market had crashed. The Internet had crashed. Nobody would return my calls. I had no friends. Either I would have a heart attack or I would simply kill myself. I had a $4 million life insurance policy. I wanted my kids to have a good life. I figured the only way that could happen was if I killed myself.

He answers the “why” by giving three causes: market, internet, and no friends. So is he an investor in internet companies? He doesn’t give a full answer to make us keep reading.

This guy is so miserable that he wants to take his own life just to leave the insurance money to his kids. How did he end up there? You can’t avoid empathizing with him. You just want to keep reading.

Reinvent Yourself by James Altucher

It was all over for me once again.

Wait! When was the last time? And why is that happening “again”? And what is “all”?

To keep building up drama, he goes on:

It was all over for me once again. Marriage was over. My bank account going down. Nobody was publishing any more of my books. Nobody was giving me any more opportunities.

If you have read James Altucher’s previous books and heard his stories, you know he’s referring to one of the multiple times he went bankrupt. That explains the “again.”

After that drama, you want to keep reading to know what he did to get back up. It’s a book about reinvention. He got back up, right?

Parting Thought

Are there any patterns in those opening lines? Yes.

  • Thought-provoking or controversial statements like in Genesis.
  • Intriguing stories like in One Hundred Years of Solitude.
  • Rising drama and tension like in James Altucher’s books.

James Altucher teaches about powerful opening lines. And he walks the talk in those two books by building up drama.

A good headline is like a welcome sign. Controversy, curiosity, blood, and drama in the first line create the first impressions in your writing. Remember, you only have one chance to give a good first impression. So, put blood and drama in your opening lines and hook your readers until the end.

4 Surprising Lessons I've Learned Recently—While Taking a Loved One to a Hospital

During a recent hospital visit, I found inspiration to write.

To keep my mind busy and productively distracted while waiting, I took out my phone and started to jot down ideas. Ideas of how to calm my mind and ideas of how hospital visits might look in 2035.

From that visit, I’ve learned four surprisingly useful (and maybe random) things about health and well-being:

#1. Insulin helps decrease potassium levels.

When we hear insulin, we think of diabetes.

But it turns out insulin helps the body absorb potassium faster. At least, that’s what a doctor explained to us. My loved one has kidney failure and her potassium levels were outside the normal range.

#2. Anemia isn’t only because of iron deficiency.

It’s one of the causes, not the main one. It could be due to genetic reasons or red blood cells dying too soon or bone disorders… or excessive bleeding.

#3. Too much exercise before bed interrupts your sleep patterns.

I found this on a study on the front page of Hacker News. I had to do something while waiting, so why not scroll down a feed?

The study doesn’t discourage exercise. It compares light exercise to high-intensity exercise within 4 hours before bed.

That won’t work as an excuse not to move your body. Sorry!

#4. When rushing, life makes you slow down.

In 2023, while finding ways to recover from burnout, I read “The Ruthless Elimination of Hurry” by John Mark Comer.

There was a line that has lived rent-free in my mind since then:

“God [or Nature or Universe] didn’t create hurry.”

I had to remember that recently. No matter how I hurry, I couldn’t change anything about what was outside my control.

One Life Lesson That Took Me 10 Years to Learn

If you don’t come up with your own plan, society, the system, or the Matrix will give you its plan:

  • Work hard
  • Get 3% raises
  • Please your bosses
  • Keep your head down
  • Wait to retire
  • Then, die

I only learned it after being laid off and recovering from burnout and stomach problems. That was my wake-up call.

I was living on autopilot. No plan at all. Stretching each job until I got bored, fired, or laid off. I was working on building somebody else’s dream.

I wish I had learned this lesson at 25, but at least I know it now.