728x90
https://leetcode.com/problems/maximum-depth-of-binary-tree
Maximum Depth of 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
이진트리 강의에 있는 코드다.
필수적인 이해가 필요하다.
test_max_depth.py
from collections import deque
from binarytree.prac import make_tree_by
def test_max_depth(lst):
root = make_tree_by(lst, 0)
if not root:
return 0
q = deque([root])
depth = 0
while q:
depth += 1
for _ in range(len(q)):
cur = q.popleft()
if cur.left:
q.append(cur.left)
if cur.right:
q.append(cur.right)
return depth
assert test_max_depth(lst=[]) == 0
assert test_max_depth(lst=[3, 9, 20, None, None, 15, 7]) == 3
structures.py
class TreeNode:
def __init__(self, val, left=None, right=None):
self.val = val
self.left = left
self.right = right
prac.py
from binarytree.structures import TreeNode
def make_tree_by(lst, idx):
parent = None
if idx < len(lst):
value = lst[idx]
if value == None:
return
parent = TreeNode(value)
parent.left = make_tree_by(lst, 2 * idx + 1) #left 인덱스 값은 2*idx+1
parent.left = make_tree_by(lst, 2 * idx + 2) #right 인덱스 값은 2*idx+2
return parent
여기서 structures.py랑 prac.py는 완벽하게 이해하고 넘어가야 한다. 다음에 또 나온다.
728x90
'알고리즘 > 파이썬' 카테고리의 다른 글
[파이썬 알고리즘]226.leetcode - 이진 트리 반전 (0) | 2022.05.24 |
---|---|
[파이썬 알고리즘] 이진트리 기초 개념(2) (0) | 2022.05.24 |
[파이썬 알고리즘] 이진트리 기초 개념(1) (0) | 2022.05.23 |
[파이썬 알고리즘] 백준-9095- 1,2,3 더하기 (0) | 2022.05.21 |
[파이썬 알고리즘] 78.leetcode - 부분집합 (0) | 2022.05.20 |