Tags: LeetCode DSA Binary Trees
Prompt:
Diameter of Binary Tree
EasyTopicsCompany TagsHints
The diameter of a binary tree is defined as the length of the longest path between any two nodes within the tree. The path does not necessarily have to pass through the root.
The length of a path between two nodes in a binary tree is the number of edges between the nodes. Note that the path can not include the same node twice.
Given the root of a binary tree root, return the diameter of the tree.
Example 1:
Input: root = [1,null,2,3,4,5]
Output: 3Explanation: 3 is the length of the path [1,2,3,5] or [5,3,2,4].
Example 2:
Input: root = [1,2,3]
Output: 2Solution:
/**
* 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 {
public:
int diameterOfBinaryTree(TreeNode* root)
{
int best = 0;
countDepth(root, best);
return best;
}
int countDepth(TreeNode* root, int& best)
{
if(root == nullptr)
{
return 0;
}
int left = countDepth(root->left, best);
int right = countDepth(root->right, best);
int sum = left + right;
if(sum > best)
{
best = sum;
}
return 1 + max(left, right);
}
};
Explanation:
So this one is another depth first search algorithm here pretty much, in essence you recursively go down and down until you hit an empty node right, you do so for both the left and the right, so you count the farthest that you can go from each left node and the farthest that you can code from each right node right. This then is compared at each new node hit, and you sum it up so you can then have a new best each time the function call gets hit pretty much, unless you’re going into a branch that is smaller than one you returned from.
Basically though, you just use the helper function in order to find the greatest distance that you can go between two different nodes in the tree, you add them up, compare that value with your current best, if you have a new current best then you go ahead and update it, if you do not then you don’t, and each time you return whatever value is greater from that node, so the left or the right, you basically work your way up the tree counting.
So obviously this leads us to a great old O(n) time and then O(h) space which is the number of difference recursive calls that end up happening and getting put on the stack.