So I was solving some tree question requires recursion. I expected lines below my recursive code to run but it doesn't wwhen tree[node.left] is None.
See that current node's value is D while left and right are None
When I execute this code,
it returns to the previous call stack without going to the pre_order(tree[node.right])
why??
let's observe the code
def pre_order(node):
if node:
print(node.value, end='')
pre_order(tree[node.left])
pre_order(tree[node.right])
So if there is a node, we print the vvalue and do recursive calls for its left and right children as such
1)Print the value of the current node.
2)Recursively call pre_order for the left child if it exists (tree[node.left] is not None).
3)Recursively call pre_order for the right child if it exists (tree[node.right] is not None).
But these recursive calls will only be executed if there are children (i.e.e not None)
So if left child is None, the recursive call for the right child is automatically skipped and returns to previous call stack.
so put an if statement like I explained a bit more there
## root->left->right
def pre_order(node):
print(node.value, end='')
if node.left:
pre_order(tree[node.left])
if node.right:
pre_order(tree[node.right])
ok good revision useful stuff