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 static int wing=[]()
11 {
12     std::ios::sync_with_stdio(false);
13     cin.tie(NULL);
14     return 0;
15 }();
16 
17 class Solution 
18 {
19 public:
20     int maxdiadepth=0;
21     int diameterOfBinaryTree(TreeNode* root) 
22     {
23         countheight(root);
24         return maxdiadepth;
25     }
26     
27     int countheight (TreeNode* root)
28     {
29         if(root==NULL)
30             return 0;
31         int leftdepth=countheight(root->left);
32         int rightdepth=countheight(root->right);
33         maxdiadepth=max(maxdiadepth,leftdepth+rightdepth);
34         return 1+max(leftdepth,rightdepth);
35     }
36 };

递归求出以每个节点为转折点的最大直径长,取这些最大值中的最大值即可。

posted on 2018-06-04 19:17  高数考了59  阅读(132)  评论(0)    收藏  举报