[Python] Why does assignment to outer variables not take effect in recursive algorithm?

Discussão em 'Python' iniciado por Stack, Fevereiro 17, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to solve a interview question: how to convert a BST to a double linked list. Below is my code. I am really confused about how python recursion works. Why after the convert2DoubleLst_recursive , the prev and head remain to be None, I have assigned a new value to these two variables, why after this method call, I cannot save the change. I remembered that python pass arguments by reference, but why here I cannot save the changes. Many thanks in advance.

    def convert2_recursive(node):
    prev,head=None,None
    convert2DoubleLst_recursive(node,prev,head)
    end=head.lChild
    printList(head,end)

    def convert2DoubleLst_recursive(node,prev,head):
    if node:
    convert2DoubleLst_recursive(node.lChild,prev,head)
    node.lChild=prev
    if prev:
    prev.rChild=node
    else:
    head=node
    nextNode=node.rChild
    head.lChild=node
    node.rChild=head
    prev=node
    convert2DoubleLst_recursive(nextNode,prev,head)

    Continue reading...

Compartilhe esta Página