Skip to content

Commit 7c4d98f

Browse files
committed
added 0104_maximum_depth_of_binary_tree.py
1 parent 45551c4 commit 7c4d98f

File tree

1 file changed

+82
-0
lines changed

1 file changed

+82
-0
lines changed
Lines changed: 82 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,82 @@
1+
"""
2+
Given the root of a binary tree, return its maximum depth.
3+
4+
A binary tree's maximum depth is the number of nodes along
5+
the longest path from the root node down to the farthest leaf node.
6+
7+
Example 1:
8+
Input: root = [3,9,20,null,null,15,7]
9+
Output: 3
10+
11+
Example 2:
12+
Input: root = [1,null,2]
13+
Output: 2
14+
15+
Constraints:
16+
* The number of nodes in the tree is in the range [0, 10^4]
17+
* -100 <= Node.val <= 100
18+
"""
19+
20+
class Solution:
21+
# O(2^n) solution, iterative
22+
# Use a stack to keep track of every path from the
23+
# root to each leaf
24+
#def maxDepth(self, root: Optional[TreeNode]) -> int:
25+
# if root is None:
26+
# return 0
27+
#
28+
# left_done = {}
29+
# right_done = {}
30+
#
31+
# stack = [root]
32+
# max_depth = 0
33+
#
34+
# while len(stack):
35+
# curr = stack[-1]
36+
#
37+
# if not curr in left_done:
38+
# left_done[curr] = True
39+
#
40+
# if curr.left:
41+
# stack.append(curr.left)
42+
# elif curr.right:
43+
# right_done[curr] = True
44+
# stack.append(curr.right)
45+
# else:
46+
# max_depth = max(max_depth, len(stack))
47+
# stack.pop()
48+
# elif not curr in right_done:
49+
# right_done[curr] = True
50+
#
51+
# if curr.right:
52+
# stack.append(curr.right)
53+
# else:
54+
# max_depth = max(max_depth, len(stack))
55+
# stack.pop()
56+
# else:
57+
# stack.pop()
58+
#
59+
# return max_depth
60+
61+
# O(2^n) solution, recursive with a helper function
62+
#def maxDepth(self, root: Optional[TreeNode]) -> int:
63+
# return self.findMaxDepth(root, 0)
64+
#
65+
#def findMaxDepth(self, node, count):
66+
# if node is None:
67+
# return count
68+
#
69+
# left = self.findMaxDepth(node.left, count + 1)
70+
# right = self.findMaxDepth(node.right, count + 1)
71+
#
72+
# return max(left, right)
73+
74+
# O(2^n) solution, recursive
75+
def maxDepth(self, root: Optional[TreeNode]) -> int:
76+
if root is None:
77+
return 0
78+
79+
left = self.maxDepth(root.left) + 1
80+
right = self.maxDepth(root.right) + 1
81+
82+
return max(left, right)

0 commit comments

Comments
 (0)