Skip to content

Instantly share code, notes, and snippets.

@ttsugriy
Created January 13, 2019 06:49
Show Gist options
  • Select an option

  • Save ttsugriy/e1a3e2f4f61cfda6ad70c698ee10de8a to your computer and use it in GitHub Desktop.

Select an option

Save ttsugriy/e1a3e2f4f61cfda6ad70c698ee10de8a to your computer and use it in GitHub Desktop.
class Solution {
private:
struct Result { int diameter; int depth; };
Result maxDiameterAndDepth(const TreeNode* root) const {
if (root == nullptr) return {0, 0};
auto leftResult = maxDiameterAndDepth(root->left);
auto rightResult = maxDiameterAndDepth(root->right);
return {
max({leftResult.diameter, rightResult.diameter, leftResult.depth + rightResult.depth}),
1 + max(leftResult.depth, rightResult.depth)
};
}
public:
int diameterOfBinaryTree(const TreeNode* root) const {
return maxDiameterAndDepth(root).diameter;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment