Python recursion

whitehousechef·2023년 11월 4일
0

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

https://velog.io/@whitehousechef/%EB%B0%B1%EC%A4%80-1991%EB%B2%88-%ED%8A%B8%EB%A6%AC-%EC%88%9C%ED%9A%8C

## 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])

revisited jan 18th 2024

ok good revision useful stuff

0개의 댓글