I'm trying to understand following binary search tree node insertion implementation in Python. I have placed a few print statements within the insert function. I could understand the first two prints generated by two insert calls but I couldn't understand third print generated seems before 3rd insert call. The implementation with debug prints looks as follows:
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
def insert(root, node):
if root is None:
root = node
return root
if node.value < root.value:
root.left = insert(root.left, node)
print("left: " + str(root.left.value))
if node.value > root.value:
root.right = insert(root.right, node)
print("right: " + str(root.right.value))
return root
root = Node(50)
insert(root, Node(10))
insert(root, Node(2))
insert(root, Node(80))
insert(root, Node(15))
insert(root, Node(60))
insert(root, Node(90))
The code prints:
left: 10
left: 2
left: 10
right: 80
right: 15
left: 10
left: 60
right: 80
right: 90
right: 80
My understanding so far:
insert(root, Node(10))(i)
__init__with value = 10 called. Since root is already set to 50, program gets inside second if condition with 10<50.(ii) recursive insert function is called with root.left as None and node value as 10. Since root.left is None now, program gets in to first if condition and root gets value 10. This finishes the recursive call and program executes next statement which is
print("left: " + str(root.left.value))this prints 10. Program evaluates third if condition as false as expected and finishes the function call for the insertion of 10.insert(root, Node(2))(i)
__init__with value=2 called. Program gets inside second if condition with 2<50.(ii) recursive insert function is called with root.left as 10 and node value as 2. Program again gets in to second if condition with 2<10.
(iii) recursive insert function is called again with root.left as None and value as 2. Now program gets in to first if condition and root gets value 2. This finishes the recursive repeat calls and program executes next print statement
print("left: " + str(root.left.value))which prints 2.(iv) Now as expected program evaluates third if condition as false and successfully calls return.
But, before startinginsert(root, Node(80)), it again goes back to print statement in second if condition and prints a 10.
I did not get this, that why after finishing (or is it not?) the function call it is going back to the print statement again?