forked from alqamahjsr/Algorithms
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path559_Maximum_Depth_of_N-ary_Tree.py
More file actions
46 lines (38 loc) · 1.05 KB
/
Copy path559_Maximum_Depth_of_N-ary_Tree.py
File metadata and controls
46 lines (38 loc) · 1.05 KB
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
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
# Bottom-Up approach
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if root is None:
return 0
maxDepthOfChildren = 0
for child in root.children:
depth = self.maxDepth(child)
maxDepthOfChildren = max(maxDepthOfChildren, depth)
return maxDepthOfChildren + 1
# Top-Down approach
class Solution(object):
def maxDepth(self, root):
"""
:type root: Node
:rtype: int
"""
if root is None:
return 0
return self.maxDepthHelper(root, 1, 1)
def maxDepthHelper(self, root, depth, maxDepth):
if root is None:
return maxDepth
maxDepth = max(depth, maxDepth)
for child in root.children:
maxDepth = self.maxDepthHelper(child, depth + 1, maxDepth)
return maxDepth