I have not found any related questions yet.
So the problem is: given an incomplete binary tree, say the root of the tree, how can I convert it into a list in level order in Python such that the empty nodes (missing nodes in that level) are represented as "None" in the list.
For example, I have this tree:
1
/ \
4 0.52
/ \ / \
2.5
I want to get the following list:
[1, 4, 0.52, None, 2.5, None, None]
by using some function like:
list = toList(root)
In addition, I have tree structured like this:
class TreeNode:
def __init__(self, value, isLeaf):
self.left = None
self.right = None
self.value = value
self.isLeaf = isLeaf
And borrow the solution from another post (to a list without 'None' taken place):
def toList(root):
node_list = []
thislevel = [root]
while thislevel:
nextlevel = list()
for n in thislevel:
# print(n.value)
node_list.append(n.value)
if n.left:
nextlevel.append(n.left)
if n.right:
nextlevel.append(n.right)
# print
thislevel = nextlevel
return node_list
my_list = toList(root)
print(my_list)
This gives the following so far:
[1, 4, 0.52, 2.5]
I am stuck here, don't know how to properly insert 'None' into the list...
Thanks!
Nonevalues for the children of the2.5node? Is the 2.5 node somehow different than the0.52which does contributeNoneto the final list?root?, It's too abstract.2.5is at the bottom of the tree, it does not have any 'None's attached to it. Whereas0.52is in the middle of the tree so we should consider both of its children are missing