Created
November 19, 2023 16:00
-
-
Save braddotcoffee/71857ce19146ec52312334c8835813a5 to your computer and use it in GitHub Desktop.
199. Binary Tree Right Side View
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from collections import deque | |
| # 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 append_or_overwrite(self, node: TreeNode, depth: int, seen: List[int]): | |
| if len(seen) == depth: | |
| seen.append(node.val) | |
| seen[depth] = node.val | |
| def rightSideView(self, root: Optional[TreeNode]) -> List[int]: | |
| if root is None: | |
| return list() | |
| queue = deque([(0, root)]) | |
| seen = [root.val] | |
| while len(queue) > 0: | |
| depth, curr_node = queue.popleft() | |
| if curr_node is None: | |
| continue | |
| next_depth = depth + 1 | |
| queue.append((next_depth, curr_node.left)) | |
| queue.append((next_depth, curr_node.right)) | |
| if curr_node.left is not None: | |
| self.append_or_overwrite(curr_node.left, next_depth, seen) | |
| if curr_node.right is not None: | |
| self.append_or_overwrite(curr_node.right, next_depth, seen) | |
| return seen | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment