Solution2: BFS(one queue + traverse current level by storing length)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
classSolution: defrightSideView(self, R: Optional[TreeNode]) -> List[int]: ifnot R: return [] Q=deque([R]) ans=[] while Q: L=len(Q) for i inrange(L): C=Q.popleft() if i==L-1: # it is the right most node in current level ans.append(C.val) if C.left: Q.append(C.left) if C.right: Q.append(C.right) return ans
Solution3: BFS(one queue + None sentinel)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
classSolution: defrightSideView(self, R: Optional[TreeNode]) -> List[int]: ifnot R: return [] Q=deque([R,None]) ans=[] while Q: C=Q.popleft() while C isnotNone: if C.left isnotNone: Q.append(C.left) if C.right isnotNone: Q.append(C.right) prev=C C=Q.popleft() ans.append(prev.val) iflen(Q)>0: Q.append(None) return ans
classSolution: defrightSideView(self, R: Optional[TreeNode]) -> List[int]: if R isNone: return [] Q=deque([R]) ans=[] while Q: N=deque() ans.append(Q[-1].val) while Q: C=Q.popleft() if C.left: N.append(C.left) if C.right: N.append(C.right) Q=N return ans # or classSolution: defrightSideView(self, R: Optional[TreeNode]) -> List[int]: if R isNone: return [] Q=deque([R]) ans=[] while Q: N=deque() while Q: C=Q.popleft() if C.left: N.append(C.left) if C.right: N.append(C.right) #last poped node is the right most node ans.append(C.val) Q=N return ans