-
-
Notifications
You must be signed in to change notification settings - Fork 48
Expand file tree
/
Copy path0104-maximum-depth-of-binary-tree.py
More file actions
67 lines (56 loc) · 1.8 KB
/
0104-maximum-depth-of-binary-tree.py
File metadata and controls
67 lines (56 loc) · 1.8 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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# time complexity: O(n)
# space complexity: O(logn)
from typing import Optional
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
def longestPath(node: Optional[TreeNode]):
if not node:
return 0
leftPath = longestPath(node.left)
rightPath = longestPath(node.right)
return max(leftPath, rightPath)+1
return longestPath(root)
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def __init__(self):
self.nextItem = []
self.maxDepth = 0
def nextMaxDepth(self):
if not self.nextItem:
return self.maxDepth
nextNode, nextLvl = self.nextItem.pop(0)
nextLvl += 1
self.maxDepth = max(self.maxDepth, nextLvl)
if nextNode.left:
self.nextItem.append((nextNode.left, nextLvl))
if nextNode.right:
self.nextItem.append((nextNode.right, nextLvl))
return self.nextMaxDepth()
def maxDepth(self, root):
if not root:
return 0
self.nextItem = []
self.maxDepth = 0
self.nextItem.append((root, 0))
return self.nextMaxDepth()
# time complexity: O(n)
# space complexity: O(n)
class Solution:
def maxDepth(self, root: TreeNode) -> int:
stack = []
if root is not None:
stack.append((1, root))
depth = 0
while stack != []:
currDepth, root = stack.pop()
if root is not None:
depth = max(depth, currDepth)
stack.append((currDepth + 1, root.left))
stack.append((currDepth + 1, root.right))
return depth