leetcode 543. 二叉树的直径

题目描述:

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

示例 :
给定二叉树

1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。

注意:两结点之间的路径长度是以它们之间边的数目表示。

 

思路分析:

这道题翻译一下就是二叉树每个结点左右子树高度和的最大值。

 

代码:

 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 maxh=0;
13     int height(TreeNode* root)
14     {
15         if(root == nullptr)
16             return 0;
17         int l = height(root->left);
18         int r = height(root->right);
19         maxh = max(maxh, l+r);
20         return max(l, r)+1;
21     }
22     int diameterOfBinaryTree(TreeNode* root) {
23         if(root == nullptr)
24             return 0;
25         height(root);
26         return maxh;
27     }
28 };

 

posted @ 2019-08-30 16:35  Fzu_LJ  阅读(149)  评论(0编辑  收藏  举报