# 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 not root: return [] stack, ans = [root], [] while stack: tmp = [] cur = stack[-1] ans.append(cur.val) for node in stack: if node.left: tmp.append(node.left) if node.right: tmp.append(node.right) stack = tmp return ans