算法思想:
深度优先搜索
C++
/**
* 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 res;
int diameterOfBinaryTree(TreeNode* root) {
int tmp = count_depth(root);
return res;
}
int count_depth(TreeNode* root) {
if (root == nullptr) return 0;
int left_max_depth = count_depth(root->left);
int right_max_depth = count_depth(root->right);
res = max(res, left_max_depth + right_max_depth);
return max(left_max_depth, right_max_depth) + 1;
}
};