Time Complexity:
Space Complexity:
# 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
from collections import deque
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root is None: return []
ans = list()
queue = deque()
queue.append([root, 0]) # 0: node, 1: depth
curDepth = 0
while queue:
node, depth = queue.popleft()
if node.right is not None:
queue.append([node.right, depth + 1])
if node.left is not None:
queue.append([node.left, depth + 1])
if depth == curDepth:
ans.append(node.val)
curDepth += 1
return ans
Time Complexity:
Space Complexity:
# 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
from collections import deque
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
if root is None: return []
ans = list()
q = deque()
q.append(root)
while q:
n = len(q)
node = None
# 같은 depth의 node를 전부 처리해준다.
for i in range(n):
node = q.popleft()
if node.left is not None:
q.append(node.left)
if node.right is not None:
q.append(node.right)
ans.append(node.val)
return ans
Time Complexity:
Space Complexity: - function call로 인한 stack
# 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
from collections import deque
class Solution:
def rightSideView(self, root: TreeNode) -> List[int]:
res=[]
def dfs(node, depth):
if not node:
return
if depth - 1 == len(res):
res.append(node.val)
else:
res[depth - 1] = node.val
dfs(node.left, depth + 1)
dfs(node.right, depth + 1)
dfs(root, 1)
return res