LeetCode 543. Diameter of Binary Tree
Solution1:我的答案
思路和方法就是同124题的
/**
* 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) {
if (!root) return 0;
int ans = 0;
my_longpath(root, ans);
return ans;
}
int my_longpath(TreeNode* root, int& ans) {
if (!root) return 0;
int l = my_longpath(root->left, ans);
int r = my_longpath(root->right, ans);
ans = max(ans, l + r);
return 1 + max(l, r);
}
};