LeetCode #104 Maximum Depth of Binary Tree

Problem

Given a binary tree, find its maximum depth.

The maximum depth is the number of nodes along the longest path from the root node down to the farthest leaf node.

Example

Given binary tree [3,9,20,null,null,15,7],

1
2
3
4
5
  3
/ \
9 20
/ \
15 7

return its depth = 3.

Note

A leaf is a node with no children.

Solution1

Method: Breadth First Search

Time Complexity: O(n)

Space Complexity: O(n)

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0

dq = collections.deque([(root, 1)])
level = 1

while dq:
node, level = dq.popleft()

if node.left:
dq.append((node.left, level + 1))
if node.right:
dq.append((node.right, level + 1))

return level

Solution2

Method: Depth First Search

Time Complexity: O(n)

Space Complexity: O(n)

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
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None

class Solution:
def maxDepth(self, root):
"""
:type root: TreeNode
:rtype: int
"""
if not root:
return 0

stack = [(root, 1)]
ret = level = 1

while stack:
node, level = stack.pop()
if ret < level:
ret = level
if node.left:
stack.append((node.left, level + 1))
if node.right:
stack.append((node.right, level + 1))

return ret