I am trying to find the right side view of a BST. I am able to get a working solution but I noticed a perculiatity with using
for i in q: vs for i in range(len(q))
To elaborate the below code works
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 rightSideView(self, root: Optional[TreeNode]) -> List[int]:
if root == None:
return []
result = []
q = []
q.append(root)
while len(q):
for _ in range(len(q)):
node = q.pop(0)
if node.left != None:
q.append(node.left)
if node.right != None:
q.append(node.right)
result.append(node.val)
return result
but then when I change the below
for _ in range(len(q)):
to
for _ in (q):
as shown below
if root == None:
return []
result = []
q = []
q.append(root)
while len(q):
for _ in (q):
node = q.pop(0)
if node.left != None:
q.append(node.left)
if node.right != None:
q.append(node.right)
result.append(node.val)
return result
I know longer get the right side view. Anyone have any idea why this is the case.
For example with the input
Input: root = [1,2,3,null,5,null,4]
I get the output using the range(len(q)) code Output: [1,3,4]
but when I try using the range(q) code I get the output Output: [2,5,4]