I am trying to write a simple method to link the nodes of a tree together in this way:
- Every leaf is linked to the previous and the next leaf in the tree
- Every non-leaf is linked to the previous and the next leaf in the tree
For example, if we have this tree:
A
/ | \
B C D
/ \ / \
E F G H
|
I
This should be the result of the method:
- B.nextToken = E
- C.prevToken = B
- E.nextToken = F
- E.prevToken = B
- F.nextToken = I
- C.nextToken = I
- H.prevToken = I
Here is the method code:
prevToken = None
def depthFirstTraverseTokenLinking(tree):
global prevToken
if len(tree.children) == 0:
tree.prevToken = prevToken
if prevToken != None :
prevToken.nextToken = tree # Is something wrong with this line?
prevToken = tree
return
for c in tree.children:
depthFirstTraverseTokenLinking(c)
tree.prevToken = tree.children[0].prevToken
tree.nextToken = tree.children[-1].nextToken
For some strange reason, the non-leaves aren't linked to the next leaves, for example:
- C.nextToken = None
Although
- F.nextToken = I
I wonder why is that happening? The last lines at the end of the recursive function should grantee that a parent will have the same next as its last child!
globalhere? Why not just have a kwargdepthFirstTraverseTokenLinking(tree, prevToken=None)?