29. 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 the tree. It may or may not pass through the root.

Example 1:

Input : root = [1, 2, 3, 4, 5]

Output : 3

Explanation : The path length between node 4 and 3 is of length 3.

There are other ways to reach the solution.

Example 2:

Input : root = [1, 2, 3, null, 4, null, 5]

Output : 4

Explanation : The path length between node 4 and 5 is of length 4.

Now Your Turn!

Pick the correct output for the given input

Input : root = [5, 1, 2, 8, 3, null, 5, null, 4]

Still unsure what the problem is asking ?

Let’s go through a few more examples, step by step, to make it clearer.

Constraints:

  • 1 <= Number of Nodes <= 104
  • -100 <= Node.val <= 100

Hints

Frequently Occurring Doubts

Interview Follow-up Questions

Fun Facts

0
/**
* Definition for a binary tree node.
* struct TreeNode {
* int data;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int val) : data(val) , left(nullptr) , right(nullptr) {}
* };
**/
 
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root) {
//your code goes here
}
};
Test Case

Input:

Root