-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathMaximum Depth of N-ary Tree.py
48 lines (38 loc) · 1.05 KB
/
Maximum Depth of N-ary Tree.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
"""
# Definition for a Node.
class Node:
def __init__(self, val=None, children=None):
self.val = val
self.children = children
"""
#DFS
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root is None:
return 0
def dfs(r):
if not r.children:
return 1
depth = 0
for child in r.children:
depth = max(depth, dfs(child) + 1)
return depth
return dfs(root)
#BFS
class Solution:
def maxDepth(self, root: 'Node') -> int:
if root is None:
return 0
def bfs(r):
q = []
q.append(root)
level = 0
while q != []:
num_nodes = len(q)
level += 1
for _ in range(num_nodes):
node = q.pop(0)
for child in node.children:
q.append(child)
return level
return bfs(root)