python - traversing through a tree -


i want write function returns elements in tree in list. i'm not allowed use global variables though. here's tried:

def traverse(current node):         if no left child , no right child:         return current nodes data     else:         if both left child , right child exist:             return [current nodes data,left_child.traverse(),right_child._traverse()]         elif no left child:   return [current node's data,right_child.traverse()]         elif no right child:  return [current node's data,left_child.traverse()] 

we used example: (root 2, left child 1, right child 3 , right child of right child 4)

    2 1      3           4 

calling traverse on tree returned this:

[2, 1, [3, 4]]

so problem can't fit within 1 list.

edit: here of node functions can called: node.data, node.left, node.right

instead of returning list of values, want pass in array , recursively append values array:

def traverse(node, arr):     if node.left:         traverse(node.left, arr)     arr.append(node.data)     if node.right:         traverse(node.right, arr)     return arr # convenience don't have store arr 

you list calling:

traverse(node, []) 

Comments

Popular posts from this blog

monitor web browser programmatically in Android? -

Shrink a YouTube video to responsive width -

wpf - PdfWriter.GetInstance throws System.NullReferenceException -