[Python] Infinite loop in multiple assignment in one line

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

  1. Stack

    Stack Membro Participativo

    I used these two versions of code in a LeetCode probleme.

    1.

    node.right = rights.pop()
    node = node.right


    node = node.right = rights.pop()


    The first one got accepted but the second one went into an infinite loop and got time limit exceeded. But aren't they exactly the same???

    The whole code is as follows:

    # Definition for a binary tree node.
    # class TreeNode:
    # def __init__(self, val=0, left=None, right=None):
    # self.val = val
    # self.left = left
    # self.right = right
    class Solution:
    def flatten(self, root: Optional[TreeNode]) -> None:
    """
    Do not return anything, modify root in-place instead.
    """
    rights = []
    node = root
    while node:
    if node.right:
    rights.append(node.right)
    if node.left:
    node.right = node.left
    node.left = None
    node = node.right
    elif len(rights):
    node = node.right = rights.pop()
    '''
    node.right = rights.pop()
    node = node.right
    '''
    else:
    return root

    Continue reading...

Compartilhe esta Página