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
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
Share
Improve this question
asked Feb 16 at 23:50
Mouhamad KasemMouhamad Kasem
111 silver badge1 bronze badge
New contributor
Mouhamad Kasem is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
1
- This question is similar to: Python Multiple Assignment Statements In One Line. If you believe it’s different, please edit the question, make it clear how it’s different and/or how the answers on that question are not helpful for your problem. – jabaa Commented Feb 17 at 0:25
1 Answer
Reset to default 2In another language, they might be the same. But in Python,
target1 = target2 = expr
performs evaluations and assignments in this order:
- Evaluate
expr
. - Evaluate anything needed to figure out what we're assigning to for
target1
. - Assign the value from step 1 to
target1
. - Evaluate anything needed to figure out what we're assigning to for
target2
. - Assign the value from step 1 to
target2
.
That means that when you do
node = node.right = rights.pop()
Python assigns the new value to node
before deciding what node
means in node.right
. So the assignment to node.right
assigns to the right
attribute of the new node
, not the old node
.