注意对比:这题 https://blog.csdn.net/mark_GJ/article/details/105982763
上面这题是每个节点到每个叶子的路径
本题是一个节点到左边的最大路径+这个节点到右边路径的和。
题目:
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过也可能不穿过根结点。
/**
* 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 res = 0;
int TreeLength(TreeNode* root);
int diameterOfBinaryTree(TreeNode* root) {
TreeLength(root);
return res;
}
};
int Solution::TreeLength(TreeNode* root) {
if (root == NULL) {
return 0;
}
int l = TreeLength(root->left);
int r = TreeLength(root->right);
res = max(res, l+r);
return max(l, r) + 1;
}