[Leetcode] 199. Binary Tree Right Side View

서해빈·2021년 4월 17일
0

코딩테스트

목록 보기
50/65

문제 바로가기

BFS

right first order

Time Complexity: O(n)O(n)
Space Complexity: O(n)O(n)

# 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

left first order

Time Complexity: O(n)O(n)
Space Complexity: O(n)O(n)

# 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

DFS

Time Complexity: O(n)O(n)
Space Complexity: O(logn)O(\log n) - 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

0개의 댓글