-
Notifications
You must be signed in to change notification settings - Fork 0
/
maxDepth.py
54 lines (48 loc) · 1.43 KB
/
maxDepth.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File : maxDepth.py
@Time : 2024/10/11 16:49:26
@Author : Zihao Zheng
@Email : [email protected]
'''
from typing import List
from collections import deque
# class Solution():
# def levelorder(self,root)->List[List[int]]:
# if not root:
# return []
# queue=deque([root])
# result=[]
# while queue:
# level=[]
# for _ in range(len(queue)):
# cur=queue.popleft()
# level.append(cur)
# if cur.left:
# queue.append(cur.left)
# if cur.right:
# queue.append(cur.right)
# result.append(level)
# return result
class Solution():
def maxDepth(self,root):
if not root:
return 0
queue=deque([root])
depth=0
while queue:
depth+=1
for _ in range(len(queue)):
cur=queue.popleft()
if cur.left:
queue.append(cur.left)
if cur.right:
queue.append(cur.right)
return depth
def maxDepth(self,root):
if not root:
return 0
left_max=self.maxDepth(root.left)
right_max=self.maxDepth(root.right)
return 1+max(left_max,right_max)