Maximum Depth of Binary Tree
Given a binary tree, find its maximum depth.
Question
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:
Input: tree = {}
Output: 0
Explanation: The height of empty tree is 0.
Input: tree = {1,2,3,#,#,4,5}
Output: 3
Explanation: Like this:
1
/ \
2 3
/ \
4 5
it will be serialized {1,2,3,#,#,4,5}
Analyzation
Recursion
IMPORTANT PATTERN!! All binary tree problem that relates to “LEVEL” or “DEPTH” can use this pattern.
Import a deque package and use the queue structure. (Only 1 queue & BFS algorithm) See the code below.
The Code
from collections import deque
class Solution:
"""
@param root: The root of binary tree.
@return: An integer
"""
def maxDepth(self, root):
# write your code here
if root is None:
return 0
queue = deque([root])
result = []
# while queue is not empty
while queue:
level = []
for _ in range(len(queue)):
node = queue.popleft() # get the first node of the queue
level.append(node.val)
# add children of the node to queue
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
# put the same level nodes in a list
result.append(level)
return len(result)
Time & Space Complexity
- Time complexity: O(n). Remember that the best case of a Binary Tree is O(logn) since it is a balanced tree but the worst case is O(n) because it can skew to only one side.
- Space complexity: O(n). Remember that the space complexity is always about how many nodes there are in a Binary Tree. If the tree is well-balanced then it is O(logn) but the worst case will be O(n).