-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path104.maximum-depth-of-binary-tree.py
More file actions
52 lines (37 loc) · 1.18 KB
/
104.maximum-depth-of-binary-tree.py
File metadata and controls
52 lines (37 loc) · 1.18 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
from typing import Optional
# Definition for a binary tree node.
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
# recursive Solution, the iterative one basically replicates the call stack
class Solution_one:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
left = 0
right = 0
if root.left:
left = self.maxDepth(root.left)
if root.right:
right = self.maxDepth(root.right)
return max(left, right) + 1
# could also do oneliner:
# return max(self.maxDepth(root.left), self.maxDepth(root.right)) + 1
# @leet start
class Solution:
def maxDepth(self, root: Optional[TreeNode]) -> int:
if root is None:
return 0
ans = 1
stack = [(root, ans)]
while stack:
node, depth = stack.pop()
if node.right:
stack.append((node.right, depth + 1))
if node.left:
stack.append((node.left, depth + 1))
ans = max(depth, ans)
return ans
# @leet end