递归:
/**
* 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 ans;
int diameterOfBinaryTree(TreeNode* root) {
ans = 1;
depth(root);
return ans-1;//-1是因为根节点不用再上溯一次根节点了,depth里面多了一次上溯加一操作
}
int depth(TreeNode* root){
if(root == nullptr) return 0;
int l = depth(root->left);
int r = depth(root->right);
if(l+r+1 > ans) ans = l+r+1;
return max(l,r) + 1;//到底后返回上一节点,这时候子树depth要加1,因为子树跟跟节点之间有一步距离
}
};