DFS解法
代码语言:javascript
复制/**
* 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) {
if (root == nullptr) return 0;
int left = dfs(root->left);
int right = dfs(root->right);
int depth = max(left, right) 1;
if(max_len < left right)
max_len = left right;
return depth;
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return max_len;
}
};