Given the root of a binary tree, return 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.
The length of a path between two nodes is represented by the number of edges between them.
Example 1:
Input: root = [1,2,3,4,5] Output: 3 Explanation: 3 is the length of the path [4,2,1,3] or [5,2,1,3].
Example 2:
Input: root = [1,2] Output: 1
Constraints:
[1, 104].-100 <= Node.val <= 100When you get asked this question in a real-life environment, it will often be ambiguous (especially at FAANG). Make sure to ask these questions in that case:
Imagine you need to find the widest path between any two leaves in a family tree structure. The brute force approach involves testing every single pair of nodes in the entire tree to measure the distance between them.
Here's how the algorithm would work step-by-step:
class TreeNode:
def __init__(self, tree_value=0, left_node=None, right_node=None):
self.val = tree_value
self.left = left_node
self.right = right_node
def diameter_of_binary_tree(root_node):
def get_all_nodes(current_node, collection_list):
if current_node is None:
return
collection_list.append(current_node)
get_all_nodes(current_node.left, collection_list)
get_all_nodes(current_node.right, collection_list)
def calculate_depth(current_node):
if current_node is None:
return 0
left_depth = calculate_depth(current_node.left)
right_depth = calculate_depth(current_node.right)
return max(left_depth, right_depth) + 1
def get_distance_between(root, first_node, second_node):
def find_path(current_node, target_node, current_path):
if current_node is None:
return False
current_path.append(current_node)
if current_node == target_node:
return True
if find_path(current_node.left, target_node, current_path) or find_path(current_node.right, target_node, current_path):
return True
current_path.pop()
return False
path_to_first = []
path_to_second = []
find_path(root, first_node, path_to_first)
find_path(root, second_node, path_to_second)
index = 0
while index < len(path_to_first) and index < len(path_to_second) and path_to_first[index] == path_to_second[index]:
index += 1
return (len(path_to_first) - index) + (len(path_to_second) - index)
# Collect every node in the tree to test every possible starting position
all_tree_nodes = []
get_all_nodes(root_node, all_tree_nodes)
max_distance_found = 0
# Check every single pair of nodes to find the longest distance path
for outer_index in range(len(all_tree_nodes)):
for inner_index in range(outer_index + 1, len(all_tree_nodes)):
current_distance = get_distance_between(root_node, all_tree_nodes[outer_index], all_tree_nodes[inner_index])
if current_distance > max_distance_found:
max_distance_found = current_distance
# Return the largest recorded distance found across all tested pairs
return max_distance_foundTo find the widest path across the tree, we can explore every branching point and calculate how far the branches stretch on the left and right sides. By checking this at every single position as we travel through the tree from the bottom up, we can instantly spot the widest possible span without wasting time repeating work.
Here's how the algorithm would work step-by-step:
class Solution:
def diameterOfBinaryTree(self, root_node):
maximum_diameter = 0
def calculate_depth(current_node):
nonlocal maximum_diameter
if not current_node:
return 0
left_branch_depth = calculate_depth(current_node.left)
right_branch_depth = calculate_depth(current_node.right)
# We combine left and right depths at each junction to find the widest span through here.
current_span = left_branch_depth + right_branch_depth
if current_span > maximum_diameter:
maximum_diameter = current_span
# We return the taller branch plus one step upward so the parent can measure accurately.
return max(left_branch_depth, right_branch_depth) + 1
calculate_depth(root_node)
return maximum_diameter| Case | How to Handle |
|---|---|
| Empty or null root node | Return a diameter of zero immediately since there are no edges in an empty tree. |
| Single node binary tree with no children | Return a diameter of zero because the path length between a node and itself in terms of edges is zero. |
| Skewed binary tree resembling a linked list either fully left or fully right | The recursion correctly travels down the single branch and calculates the maximum path length without crashing. |
| Completely balanced binary tree with maximum width | The algorithm efficiently visits each node once in linear time to compute left and right subtree heights. |
| Tree where the longest path does not pass through the root node | Updating a global or state variable at every single node ensures we capture the maximum diameter anywhere in the tree. |
| Deeply nested binary tree exceeding standard recursion limits | Python or system recursion limits might be exceeded for a skewed tree of depth ten thousand, requiring stack optimization or limit adjustments. |