题目链接:https://leetcode-cn.com/problems/diameter-of-binary-tree/

给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。

 思路:返回根节点左右子树的高度和

 1 /**
 2  * Definition for a binary tree node.
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int diameterOfBinaryTree(TreeNode* root)
13     {
14         int dist=0;
15         dfs(root,dist);
16         return dist;
17     }
18     int dfs(TreeNode *root, int &dist)
19     {
20         if(root==nullptr)return 0;
21         int left=dfs(root->left,dist);
22         int right=dfs(root->right,dist);
23         dist=max(left+right,dist);
24         return max(left,right) + 1;
25     }
26 };
12-31 06:19