개발공부/algorithm

[Leetcode][python] 1161: Maximum Level of sum of a binary tree - BFS

2021. 4. 27. 19:52
  • Leetcode: 1161 - Maximum level of sum of a binary tree
  • Level: Medium
  • Link
 

Maximum Level Sum of a Binary Tree - LeetCode

Level up your coding skills and quickly land a job. This is the best place to expand your knowledge and get prepared for your next interview.

leetcode.com

My approach

  1. Iterate through the tree with a bfs approach
  2. For each level, sum up the value of each leaf update to a dictionary
  3. Sort the dictionary by the value of each level, and return the smallest level with the biggest sum.
from collections import defaultdict
class Solution:
    
    def maxLevelSum(self, root: TreeNode) -> int:
        q = [(root, 1)]
        cnt = 0
        vals = defaultdict(int)
        vals[1] = root.val

        while q:
            rt, level = q.pop(0)
            if rt.left:
                q.append((rt.left, level + 1))
                vals[level + 1] += rt.left.val
            if rt.right:
                q.append((rt.right, level + 1))
                vals[level + 1] += rt.right.val
        
        sort_orders = sorted(vals.items(), key=lambda x: x[1], reverse=True)
        return sort_orders[0][0]

저작자표시 (새창열림)

'개발공부 > algorithm' 카테고리의 다른 글

[Leetcode][python] 973: K closest point to the origin  (0) 2021.04.28
[Leetcode][python] 929: Unique email addresses  (0) 2021.04.28
[Leetcode][python] 257: binary tree paths - DFS  (0) 2021.04.27
[Leetcode][python] 733: flood fill - bfs  (0) 2021.04.25
[Leetcode][python] 690 - Employee importance - DFS  (0) 2021.04.25
'개발공부/algorithm' 카테고리의 다른 글
  • [Leetcode][python] 973: K closest point to the origin
  • [Leetcode][python] 929: Unique email addresses
  • [Leetcode][python] 257: binary tree paths - DFS
  • [Leetcode][python] 733: flood fill - bfs
so.py
so.py
실리콘 밸리에서 개발자로 살아남기 🌉 미국 유학생의 취준, 개발 공부 여정을 담습니다. #빅테크 #SW #샌프란
so.py
so.py
so.py
전체
오늘
어제
  • All (108)
    • Insights (9)
      • 미국 근무 일지 (3)
      • 국내 취업 일지 (4)
      • 휴학 일지 (1)
    • 개발공부 (87)
      • 개발 (11)
      • algorithm (76)
    • Data Science (9)
      • ML&AI (7)
      • etc (1)
    • Projects (3)
    • daily (0)

블로그 메뉴

  • 홈
  • 태그

공지사항

인기 글

태그

  • 파이썬
  • Algorithm
  • recursion
  • 리트코드
  • Baekjoon
  • dfs
  • 네이버코테
  • d2
  • DP
  • 알고리즘
  • SWEA
  • BOJ
  • tree
  • binarysearch
  • queue
  • 네이버nlp인턴
  • bfs
  • dynamicprogramming
  • Python
  • 코딩테스트
  • 백준
  • twopointer
  • greedy
  • leetcode
  • Stack
  • BERT
  • kmeans
  • nlp
  • string
  • programmers

최근 댓글

최근 글

hELLO · Designed By 정상우.
so.py
[Leetcode][python] 1161: Maximum Level of sum of a binary tree - BFS
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.