DFS解法
/**
* 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 {
private:
int max_len = 0;
public:
int dfs(TreeNode* root) {
// 叶节点返回深度0
int right = (root->left != nullptr) ? dfs(root->left) : 0;
int left = (root->right != nullptr) ? dfs(root->right) : 0;
int depth = max(left, right) + 1;
if (left + right > max_len)
max_len = left + right;
return depth;
}
int diameterOfBinaryTree(TreeNode* root) {
if (root == nullptr) return 0;
dfs(root);
return max_len;
}
};