Skip to content
Advertisement

Searching any tree in Python

I need to write a function in Python that takes a tree and an index and returns the subtree or leaf at that index.

I tried with loops and nested loops until I realized that the tree that had to run the tests was always the same:

JavaScript

which actually looks like this:

Sample tree

So all I needed to pass the tests given was this:

JavaScript

For example, for an index = (1, 1, 0) it should return the number 5 and it does.

However, I know this code won’t work for other trees or index with more than 3 elements. How could I make it work for any given tree and index?

Advertisement

Answer

You should try to use recursion.

Something like below:

JavaScript
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement