Diameter of Binary Tree - Python Solution

1. Introduction

The "Diameter of Binary Tree" problem is a well-known challenge in tree algorithms, focusing on finding the longest path between any two nodes in a binary tree. This problem does not restrict the path to pass through the root, making it an interesting case of depth-first traversal in binary trees.

Problem

Given the root of a binary tree, the objective is to return the length of the diameter of the tree. The diameter is defined as the length of the longest path between any two nodes in the tree. The length of a path is represented by the number of edges between the nodes.

2. Solution Steps

1. Implement a depth-first search algorithm to traverse the tree.

2. At each node, calculate the height of the left and right subtrees.

3. The diameter through the current node is the sum of the heights of its left and right subtrees.

4. Update the maximum diameter found during the traversal.

5. The height of a node is 1 plus the maximum height of its left or right subtree.

6. Continue the process for each node and return the maximum diameter.

3. Code Program

```java
class TreeNode {
    int val;
    TreeNode left;
    TreeNode right;
    TreeNode(int x) { val = x; }
}

class Solution {
    int maxDiameter = 0;

    public int diameterOfBinaryTree(TreeNode root) {
        maxDepth(root);
        return maxDiameter;
    }

    private int maxDepth(TreeNode node) {
        if (node == null) {
            return 0;
        }

        int leftDepth = maxDepth(node.left);
        int rightDepth = maxDepth(node.right);

        // Update the maximum diameter
        maxDiameter = Math.max(maxDiameter, leftDepth + rightDepth);

        // Return the height of the current node
        return 1 + Math.max(leftDepth, rightDepth);
    }
}

// Example Usage
public class Main {
    public static void main(String[] args) {
        Solution solution = new Solution();
        TreeNode root = new TreeNode(1);
        root.left = new TreeNode(2);
        root.right = new TreeNode(3);
        root.left.left = new TreeNode(4);
        root.left.right = new TreeNode(5);

        System.out.println("Diameter of the Binary Tree: " + solution.diameterOfBinaryTree(root));
    }
}

Output:

Diameter of the Binary Tree: 3

Explanation:

1. Depth-First Search: The maxDepth method is a DFS algorithm that computes the height of each node.

2. Diameter Calculation: At each node, the diameter is calculated as the sum of the heights of the left and right subtrees.

3. Maximum Diameter: The maxDiameter variable keeps track of the maximum diameter found during the traversal.

4. Height Computation: The height of a node is the maximum height of its left or right subtree plus one.

5. Final Result: The diameterOfBinaryTree method returns the maximum diameter of the binary tree.


Comments