expertfunda logo Top Interview Questions Binary Tree Binary Search Tree Graph

Diameter of Binary Tree

Leetcode 543. Diameter of Binary Tree

Diameter of Binary Tree

Leetcode 543. Diameter of Binary Tree : 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.

Approach #1 Using Recursion:


class Solution {
    private int diameter;

    public int diameterOfBinaryTree(TreeNode root) {
        diameter = 0;
        longestPath(root);
        return diameter;
    }

    private int longestPath(TreeNode node) {
        if (node == null)
            return 0;
        // recursively find the longest path in
        // both left child and right child
        int leftPath = longestPath(node.left);
        int rightPath = longestPath(node.right);

        // update the diameter if left_path plus right_path is larger
        diameter = Math.max(diameter, leftPath + rightPath);

        // return the longest one between left_path and right_path;
        // remember to add 1 for the path connecting the node and its parent
        return Math.max(leftPath, rightPath) + 1;
    }
}

Time Complexity: O(m) and Space Complexity: O(m)

Time complexity : O(m). A total of m nodes need to be traversed. Here, m represents the minimum number of nodes from the two given trees. Space complexity : O(m). The depth of the recursion tree can go upto m in the case of a skewed tree. In average case, depth will be O(logm).


See Video lecture


Leetcode 543. Diameter of Binary Tree

Introduction

The "Diameter of Binary Tree" problem is to find the longest path between any two nodes in a binary tree. This path may or may not pass through the root of the tree. The diameter of a binary tree is the number of nodes on the longest path between two leaves in the tree.

The solution involves traversing the tree to calculate the longest path for each node, and then computing the maximum of these paths.

Problem Statement

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.

        class TreeNode:
            def __init__(self, val=0, left=None, right=None):
                self.val = val
                self.left = left
                self.right = right
        

The tree node structure is defined as above. The task is to compute the diameter of the binary tree.

Approach

The key observation to solve this problem is that the diameter of a tree can be represented as the longest path between two nodes, which can be determined by the depth of the left and right subtrees of each node. The diameter at any node is the sum of the depths of its left and right subtrees. The overall diameter of the tree is the maximum diameter among all nodes.

The approach involves performing a depth-first search (DFS) traversal of the tree, where for each node, we calculate the depth of its left and right subtrees and update the global diameter based on the sum of these depths.

The steps for the solution are as follows:

  • Perform a depth-first traversal (DFS) on the tree.
  • At each node, calculate the depth of the left and right subtrees.
  • The diameter at each node is the sum of the depths of its left and right subtrees.
  • Update the global diameter to the maximum of its current value and the diameter at the current node.
  • Return the global diameter at the end of the traversal.

Algorithm

The algorithm follows these steps:

  1. Start by defining a helper function to calculate the depth of the left and right subtrees.
  2. For each node, compute the depths of the left and right subtrees.
  3. Calculate the diameter at each node as the sum of the left and right subtree depths.
  4. Keep track of the maximum diameter encountered during the traversal.
  5. Return the final diameter after traversing the entire tree.

This approach ensures that we compute the diameter in a single DFS pass, making it both time-efficient and space-efficient.

Example

Consider the following binary tree:

               1
              / \
             2   3
            / \
           4   5
        

- The diameter at node 4 is 0 (no children). - The diameter at node 5 is 0 (no children). - The diameter at node 2 is 2 (left depth = 1, right depth = 1). - The diameter at node 3 is 0 (no children). - The diameter at node 1 is 3 (left depth = 2, right depth = 1). - The maximum diameter of the tree is 3.

In this example, the longest path is from node 4 to node 5 through node 2, which has a length of 3.

Code Implementation

Below is the Python code to calculate the diameter of a binary tree using DFS:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

class Solution:
    def __init__(self):
        self.diameter = 0
    
    def diameterOfBinaryTree(self, root):
        # Helper function to calculate the depth of a subtree
        def depth(node):
            if not node:
                return 0
            # Recursively calculate the depth of the left and right subtrees
            left_depth = depth(node.left)
            right_depth = depth(node.right)
            
            # Update the diameter: the sum of left and right depths
            self.diameter = max(self.diameter, left_depth + right_depth)
            
            # Return the depth of the current subtree
            return max(left_depth, right_depth) + 1
        
        depth(root)
        return self.diameter
        

In this code: - The `depth` function recursively calculates the depth of each subtree. - For each node, we calculate the sum of the left and right subtree depths and update the global `diameter` variable. - The `diameterOfBinaryTree` function initiates the depth-first traversal and returns the computed diameter of the binary tree.

Time Complexity

The time complexity of this solution is O(n), where n is the number of nodes in the binary tree. This is because we visit each node exactly once during the DFS traversal.

The space complexity is O(h), where h is the height of the tree, due to the recursion stack. In the worst case, for an unbalanced tree, the height will be O(n), resulting in a space complexity of O(n). For a balanced tree, the height will be O(log n), so the space complexity will be O(log n).

Optimized Approach

The current approach is already optimal in terms of time complexity (O(n)) as we traverse the tree only once. The space complexity is determined by the recursion stack, which is O(h), where h is the height of the tree.

While there is no significant optimization possible in terms of time complexity, an iterative approach using a stack could be used to reduce the recursion overhead in cases where the tree is very deep and unbalanced.

Time Complexity (Optimized)

The time complexity remains O(n), where n is the number of nodes in the tree. The space complexity is O(h), where h is the height of the tree, which can be O(n) in the worst case (for an unbalanced tree) and O(log n) for a balanced tree.

Conclusion

The "Diameter of Binary Tree" problem is a classical tree problem that involves finding the longest path between any two nodes in the tree. The optimal solution is to perform a DFS traversal of the tree and compute the diameter at each node by summing the depths of its left and right subtrees. The time complexity of the solution is O(n), where n is the number of nodes, and the space complexity is O(h), where h is the height of the tree.