2

In python, I have a list of nested lists that represents a binary tree:

L = [0, [[1, [2, 3]], [4, [5, 6]]]]

So the tree can be seen as follows:

        0
       /  \
      1    4
     /\    /\ 
    2  3  5  6

I now want to implement a function that takes as input a level of the tree and returns all the nodes of that level:

GetNodes(0) = 0
GetNodes(1) = [1,4]
GetNodes(2) = [2,3,5,6]

Is there an easy way to do this, avoiding a brutal search on all the nested lists of L? Is there the possibility of a more standard management of binary trees in python, maybe converting my list of lists in something else?

Ulderique Demoitre
  • 1,029
  • 3
  • 11
  • 26
  • 1
    see if this can help: https://github.com/joowani/binarytree – scriptboy Jan 10 '17 at 08:47
  • Note that you can build a tree by using `collections.defaultdict`: `def tree(): return defaultdict(tree)`. Accessing elements is done via `[some_element]`. Because you want all elements of a certain level I think there is no other way than to start from the very top and traverse the tree until the specified level (is that what you meant by "brute force"?). – a_guest Jan 10 '17 at 08:50
  • It is known as level order traversing. Google it and you'll find plenty of answers – Moinuddin Quadri Jan 10 '17 at 08:58

2 Answers2

4

my solution would parse into dict

l = [0, [[1, [2, 3, [[7,8], [10,11]]]], [4, [5, 6, [9,10]]]]]
datadict = {}

def toTree(data,depth=0):
    for elem in data:
        if not isinstance(elem, int):
            toTree(elem, depth+1)
        else:
            d = depth - 1 if depth > 0 else depth
            if datadict.get(d):
                datadict[d] = datadict[d] + [elem]
            else:
                datadict[d] = [elem]

toTree(l)
print(datadict)

the output would be

{0: [0], 1: [1, 4], 2: [2, 3, 5, 6], 3: [9, 10], 4: [7, 8, 10, 11]}

and you can just use datadict.get(2) to get [2, 3, 5, 6]

3

I would go for a BFS. Will post code asap :)

Edit: Here you go

L = [0, [[1, [2, 3]], [4, [5, 6]]]]


def getLevel(k, tree):
    currentLevel = [tree[0]]
    nextLevel = tree[1]
    level = 1
    while level <= k:
        _currentLevel = []
        _nextLevel = []
        for subtree in nextLevel:
            if isinstance(subtree, list):
                _currentLevel.append(subtree[0])
                if isinstance(subtree[1], list):
                    _nextLevel.append(subtree[1])
                else:
                    _currentLevel.append(subtree[1])
            else:
                _currentLevel.append(subtree)
        currentLevel= _currentLevel
        nextLevel = _nextLevel
        level+=1
    return currentLevel


# uncomment for python 2
# print getLevel(0, L)
# print getLevel(1, L)
# print getLevel(2, L)

# uncomment python 3
print(getLevel(0, L))
print(getLevel(1, L))
print(getLevel(2, L))
deponovo
  • 1,114
  • 7
  • 23