order
is not getting updated because, unlike what you claim, it is not a global variable. By defining your recursive
function like this,
def recursive(node,order,father):
any reference to order
within the scope of that function will only modify the parameter, not the global variable. Within that function, you only modify order
in the if
branch, but use it in the else
branch. So the update to the parameter never gets passed on.
In order to use order
as a global variable, declare it as such:
def recursive(node, father):
global order
if ...
Another issue in your code - when you set values for Post_Order_List_of_Node
, you use
Post_Order_List_of_Node[order] = node
However, order
starts at 1 instead of at 0, so for the last node you'll get an error. You need to use
Post_Order_List_of_Node[order-1] = node
instead.
One inefficiency that you may or may not have noticed is in how you process nodes:
def recursive(node,father):
if len(Spanning_Tree[node]) == 0:
# Process node
else:
while(len(Spanning_Tree[node])!=0):
# Process child
In one call to recursive
, you only process the children or the node itself. Your code works because of the while
loop - you call recursive
twice for each child that has children itself. Instead of doing it that way, you could switch it to do this:
def recursive(node,father):
for child in Spanning_Tree[node]:
# process child
# process node
This has the added advantage that it does not require modifying Spanning_Tree
. However, it does require that you either make sure that you do have a tree (no cycles) or that you mark nodes as visited before you start processing any children.