Given a binary tree, you need to compute the length of the diameter of the tree. The diameter of a binary tree is the length of the longest path between any two nodes in a tree. This path may or may not pass through the root.
Example:
Given a binary tree
1 / \ 2 3 / \ 4 5
Return 3, which is the length of the path [4,2,1,3] or [5,2,1,3].
Note: The length of path between two nodes is represented by the number of edges between them.
Source
# 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
def bt_diameter(root):
"""DFS using a recursive approach
Time Complexity: O(n)
Space Complexity: O(n)
"""
def height(node):
nonlocal global_diameter
# base case
if not node:
return -1
# recursive relation
left = height(node.left)
right = height(node.right)
local_diameter = 2 + left + right
if local_diameter > global_diameter:
global_diameter = local_diameter
return 1 + max(left, right)
global_diameter = 0
height(root)
return global_diameter
Solve it both recursively and iteratively
def bt_diameter(root):
"""BFS (level traversal) using a bottom up iterative approach - see leetcode #110)
Time Complexity: O(n)
Space Complexity: O(n)
"""
global_diameter = 0
# Start with a level traversal (using a stack)
queue = [root]
for node in queue:
if not node:
continue
queue += node.left, node.right # last nodes --> full layer of "None"
# then, traverse nodes in reverse (i.e from bottom layer)and update their height
# by conv. height of bottom nodes = 0 (i.e last nodes being "None" have depth = -1)
height = {None: -1}
for node in reversed(queue):
if node:
height_left = height[node.left]
height_right = height[node.right]
height[node] = 1 + max(height_left, height_right)
local_diameter = 2 + height_left + height_right
if local_diameter > global_diameter:
global_diameter = local_diameter
return global_diameter