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?
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))
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.