Taro Logo

Diameter of Binary Tree

#131 Most AskedEasy
Topics:
TreesRecursion

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:

  • The number of nodes in the tree is in the range [1, 104].
  • -100 <= Node.val <= 100

Solution


Clarifying Questions

When 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:

  1. What should the function return if the root is null (an empty tree)?
  2. Can the binary tree be extremely skewed (e.g., acting like a linked list), and if so, do we need to worry about stack overflow from recursion depth?
  3. Are node values guaranteed to be integers, and can they be negative or zero?
  4. Could you clarify the definition of 'length of a path'—does it strictly mean the number of edges between the two nodes?
  5. Is the diameter guaranteed to be unique, or could there be multiple paths of the same maximum length?

Brute Force Solution

Approach

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:

  1. Begin by picking the first person at the very top of the family tree.
  2. Measure the distance from this person to every other person down in the tree by counting the steps of the relationship path.
  3. Write down the longest distance you found starting from this top person.
  4. Move on to the next person in the tree and repeat the exact same process of measuring the path to every other reachable person.
  5. Record the longest distance found for this new person and compare it with your previous best record, updating your record if this new path is wider.
  6. Continue this process for every single person in the tree, ensuring that every possible pair of paths is measured and checked.
  7. Once you have tested every person as a starting point, the largest recorded distance is your final answer.

Code Implementation

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_found

Big(O) Analysis

Time Complexity
O(n²) – For each of the n nodes in the tree, we measure the distance to every other reachable node by traversing downwards. For the first top node, we might visit all n-1 other nodes, and for subsequent nodes, we repeat similar extensive traversals to test all possible pairs. This repetitive checking of paths for every single person results in approximately n * n/2 operations, which simplifies to O(n²).
Space Complexity
O(n) – The space complexity is driven entirely by the recursion stack frames used during the depth-first search traversal of the tree. In the worst-case scenario where the binary tree is completely unbalanced and resembles a linear linked list, the recursive calls will reach a maximum depth of N. Therefore, the auxiliary memory consumed by the call stack scales linearly with the total number of nodes N in the tree.

Optimal Solution

Approach

To 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:

  1. Imagine you are standing at the very bottom of the tree, looking up at how many steps it takes to reach the lowest leaves.
  2. As you move upward from the bottom, ask every junction point how deep its left branch goes and how deep its right branch goes.
  3. Add those two branch depths together to figure out the total width passing directly through that specific junction point.
  4. Keep track of the widest span you discover anywhere in the tree as you continue your journey upward.
  5. Pass the height of the current branch up to the parent junction so it knows how tall it is, adding one step for the connection.
  6. Repeat this process all the way to the very top of the tree, updating your record whenever you find an even wider span.
  7. By the time you reach the top, the biggest recorded span is your final answer.

Code Implementation

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

Big(O) Analysis

Time Complexity
O(n) – In this bottom-up recursive approach, the input size n represents the total number of nodes in the binary tree. The algorithm visits every single node exactly once as it travels from the bottom leaves up to the root junction point, performing a constant amount of work to calculate branch depths and update the maximum span. This results in roughly n operations, where every node is processed in linear sequence. Simplifying this total operation count yields a final time complexity of O(n).
Space Complexity
O(H) – The auxiliary space complexity is determined by the call stack used during the recursive tree traversal, where H represents the height of the binary tree. In the worst-case scenario of a completely skewed tree, the recursion stack will grow to a maximum depth of N, leading to linear space usage. Conversely, for a perfectly balanced tree, the maximum depth of the recursive calls will be proportional to the logarithm of N, resulting in logarithmic space. Therefore, the extra memory consumed beyond the input tree itself is entirely driven by these recursive stack frames as they travel from the bottom up.

Edge Cases

Empty or null root node
How to Handle:
Return a diameter of zero immediately since there are no edges in an empty tree.
Single node binary tree with no children
How to Handle:
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
How to Handle:
The recursion correctly travels down the single branch and calculates the maximum path length without crashing.
Completely balanced binary tree with maximum width
How to Handle:
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
How to Handle:
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
How to Handle:
Python or system recursion limits might be exceeded for a skewed tree of depth ten thousand, requiring stack optimization or limit adjustments.
0/245 completed