/**
* 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 max_len = 0;
int dfs(TreeNode* root) {
if(!root) return 0;
int left_depth = dfs(root->left);
int right_depth = dfs(root->right);
max_len = max(max_len, left_depth + right_depth);
return 1 + max(left_depth, right_depth);
}
int diameterOfBinaryTree(TreeNode* root) {
dfs(root);
return max_len;
}
};
【leetcode 二叉树 C++】543. Diameter of Binary Tree
最新推荐文章于 2023-04-01 18:53:45 发布