반응형
Notice
Recent Posts
Recent Comments
- Today
- Total
작심삼일
[LeetCode] 199 | Binary Tree Right Side View | Python 본문
728x90
반응형
문제 링크: https://leetcode.com/problems/binary-tree-right-side-view/
문제
Given the root of a binary tree, imagine yourself standing on the right side of it, return the values of the nodes you can see ordered from top to bottom.
조건
- The number of nodes in the tree is in the range [0, 100].
- -100 <= Node.val <= 100
내 풀이
right view이기 때문에 오른쪽 노드부터 확인해서 오른쪽 노드가 존재하면 ans에 추가한다.
왼쪽 노드는 같은 depth일 때의 오른쪽 노드가 없다면 ans에 추가한다.
코드
# 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 []
ans = [root.val]
def recursive(root, depth):
if root.right:
if len(ans) <= depth:
ans.append(root.right.val)
recursive(root.right, depth+1)
if root.left:
if len(ans) <= depth:
ans.append(root.left.val)
recursive(root.left, depth+1)
recursive(root, 1)
return ans
728x90
반응형
'스터디 > 코테' 카테고리의 다른 글
[LeetCode] 102 | Binary Tree Level Order Traversal | Python (0) | 2022.07.13 |
---|---|
[LeetCode] 473 | Matchsticks to Square | Python (0) | 2022.07.12 |
[LeetCode] 97 | Interleaving String | Python (0) | 2022.07.07 |
[LeetCode] 509 | Fibonacci Number | Python (0) | 2022.07.06 |
[LeetCode] 135 | Candy | Python (0) | 2022.07.04 |
Comments