Skip to content

Instantly share code, notes, and snippets.

@terracotta-ko
Created April 1, 2018 16:34
gist for leetcode 543
/**
* 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 ans = 0;
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return ans;
}
int dfs(TreeNode *root) {
if(!root) {
return 0;
}
int leftDepth = dfs(root->left);
int rightDepth = dfs(root->right);
//>> calcualte the max depth
ans = max(ans, leftDepth + rightDepth);
//>> return depth
return max(leftDepth, rightDepth) + 1;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment