Skip to content

Commit 97a0c14

Browse files
committed
feat: solve DaleStudy#227 with python
1 parent 246c045 commit 97a0c14

File tree

1 file changed

+80
-0
lines changed
  • maximum-depth-of-binary-tree

1 file changed

+80
-0
lines changed

maximum-depth-of-binary-tree/EGON.py

Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
from typing import Optional
2+
from unittest import TestCase, main
3+
4+
5+
# Definition for a binary tree node.
6+
class TreeNode:
7+
def __init__(self, val=0, left=None, right=None):
8+
self.val = val
9+
self.left = left
10+
self.right = right
11+
12+
13+
class Solution:
14+
def maxDepth(self, root: Optional[TreeNode]) -> int:
15+
return self.solve_dfs_iterable(root)
16+
17+
"""
18+
Runtime: 0 ms (Beats 100.00%)
19+
Time Complexity: O(n)
20+
> 트리의 모든 노드의 갯수를 n개라고 하면, 트리의 모든 노드를 stack에 넣어 조회하므로 O(n)
21+
22+
Memory: 17.75 MB (Beats 21.97%)
23+
Space Complexity: O(n)
24+
> 최악의 경우 트리의 최대 길이가 n인 경우이므로, stack의 최대 크기가 n에 비례하므로 O(n), upper bound
25+
"""
26+
def solve_dfs_iterable(self, root: Optional[TreeNode]) -> int:
27+
max_depth = 0
28+
stack = [(root, 0)]
29+
while stack:
30+
curr_node, curr_depth = stack.pop()
31+
if curr_node is None:
32+
continue
33+
34+
if curr_node.left is None and curr_node.right is None:
35+
max_depth = max(max_depth, curr_depth + 1)
36+
continue
37+
38+
if curr_node.left:
39+
stack.append((curr_node.left, curr_depth + 1))
40+
if curr_node.right:
41+
stack.append((curr_node.right, curr_depth + 1))
42+
43+
return max_depth
44+
45+
46+
"""
47+
Runtime: 0 ms (Beats 100.00%)
48+
Time Complexity: O(n)
49+
50+
Memory: 17.90 MB (Beats 9.05%)
51+
Space Complexity: O(n)
52+
"""
53+
def solve_dfs_recursive(self, root: Optional[TreeNode]) -> int:
54+
max_depth = 0
55+
56+
def dfs(node: Optional[TreeNode], depth: int):
57+
nonlocal max_depth
58+
59+
if not node:
60+
return max_depth
61+
62+
if node.left is None and node.right is None:
63+
max_depth = max(max_depth, depth + 1)
64+
return
65+
66+
dfs(node.left, depth + 1)
67+
dfs(node.right, depth + 1)
68+
69+
dfs(root, 0)
70+
71+
return max_depth
72+
73+
74+
class _LeetCodeTestCases(TestCase):
75+
def test_1(self):
76+
self.assertEqual(True, True)
77+
78+
79+
if __name__ == '__main__':
80+
main()

0 commit comments

Comments
 (0)