Categories:

Tags:



Problem

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.

Constraints

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

Solution

The problem Diameter of Binary Tree can by solved by using a depth-first search. Let p be a parent node in a given binary tree and c1 and c2 its child nodes. Then, the path that decides the diameter of p can either pass or not pass p. If the longest path passes p, then the diameter can be gained with depth(c1) + depth(c2) where depth(n) is a maximum depth of node n. If, on the other hand, the longest path does not pass p, then the diameter of p becomes max(diameter(c1), diameter(c2)) where diameter(n) is a diameter of node n, since the longest path must still be a part of either c1 or c2. Therefore, by applying depth-first search, we’re able to determine the diameter from the leaves up to the root node.

Implementation

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution
{
  private:
    int diameter;

  public:
    int helper(TreeNode *root)
    {
        if (root == NULL)
            return -1;

        int ldepth = helper(root->left) + 1;
        int rdepth = helper(root->right) + 1;
        diameter = max(diameter, ldepth + rdepth);

        return max(ldepth, rdepth);
    }

    int diameterOfBinaryTree(TreeNode *root)
    {
        diameter = 0;
        helper(root);

        return diameter;
    }
};