🎉 One-stop destination for all your technical interview Preparation 🎉
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.
class Solution {
private:
int height(TreeNode* root)
{
if (root == NULL) return 0;
return 1 + max(height(root->left), height(root->right));
}
int diameter(TreeNode* root)
{
if (root == NULL) return 0;
int leftHeight = height(root->left);
int rightHeight = height(root->right);
int leftDig = diameter(root->left);
int rightDig = diameter(root->right);
return max(1 + leftHeight + rightHeight, max(leftDig, rightDig));
}
public:
int diameterOfBinaryTree(TreeNode* root)
{
if (root == NULL) return 0;
// O(N^2)
return diameter(root)-1;
}
};
class Solution {
private:
int height(TreeNode* root, int& ans)
{
if (root == NULL) return 0;
int leftHeight = height(root->left, ans);
int rightHeight = height(root->right, ans);
// keep track of the maximum diameter of the tree
ans = max(ans, leftHeight + rightHeight);
return max(leftHeight, rightHeight) + 1;
}
public:
int diameterOfBinaryTree(TreeNode* root)
{
int ans = 0;
height(root, ans);
return ans;
}
};