Technical Interview Question:
Given a binary tree, write a function to find the diameter of the binary 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.
class TreeNode:
def __init__(self, value=0, left=None, right=None):
self.value = value
self.left = left
self.right = right
def diameter_of_binary_tree(root):
def height(node):
nonlocal max_diameter
if not node:
return 0
left_height = height(node.left)
right_height = height(node.right)
max_diameter = max(max_diameter, left_height + right_height)
return 1 + max(left_height, right_height)
max_diameter = 0
height(root)
return max_diameter
Explanation:
In this solution, we define a nested function height that takes a node as an input and returns the height of the tree rooted at that node. Within height, we recursively calculate the height of the left and right subtrees and update the max_diameter variable with the sum of their heights if it exceeds the current maximum diameter.
Then, we call height on the root of the binary tree to calculate the maximum diameter, and return the result.
The time complexity of this solution is O(n), where n is the number of nodes in the binary tree, since we visit each node once.