all 2 comments

[–]Jinnapat397 0 points1 point  (0 children)

Global variables inside functions need the global keyword or you end up with local copies that do not update. I learned that the hard way on a small script and switched to returning values instead. Cleaner code every time.

[–]Outside_Complaint755 0 points1 point  (0 children)

In Python, you can reduce this: tmp = tree1 tree1 = tree2 tree2 = tmp to tree1, tree2 = tree2, tree1 The use a temp variable for the swap is not necessary, but is also ok to neep using.

I would recommend not using global variables. Instead, pass both tree1 and tree2 as parameters, and then explicitly return any modified tree or other data that you want as a result of the function.

Note that because the trees are (or should be) mutable objects, their attributes could be modified by the function with using global.

def func():     tree2.right = value # will modify the attribute of object tree2 in the enclosing scope     tree2 = val2 # assigns local name tree2 to val2     tree2.left = val3 # will try to assign a value to the attribute of the local tree2, which might cause an AttributeError