Leetcode 543 Solution
This article provides solution to leetcode question 543 (diameter-of-binary-tree)
Access this page by simply typing in "lcs 543" in your browser address bar if you have bunnylol configured.
Leetcode Question Link
https://leetcode.com/problems/diameter-of-binary-tree
Solution
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
int diameterOfBinaryTree(TreeNode* root, int& depth)
{
if (root == NULL)
{
depth = 0;
return 0;
}
int left_depth;
int left_diameter = diameterOfBinaryTree(root->left, left_depth);
int right_depth;
int right_diameter = diameterOfBinaryTree(root->right, right_depth);
depth = max(left_depth, right_depth) + 1;
int diameter = max(left_diameter, right_diameter);
return max(diameter, left_depth + right_depth);
}
int diameterOfBinaryTree(TreeNode* root) {
int depth;
return diameterOfBinaryTree(root, depth);
}
};