微软面试题: LeetCode 543. 二叉树的直径出现次数:3

题目描述:

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

这条路径可能穿过也可能不穿过根结点。

分析:

  本题和  124. 二叉树中的最大路径和  是一样的思想 ,124 题是在二叉树中 求一条路径 使得这条路径上的

节点和最大。本题是在二叉树树中找一条路径 使得这条路径上的边的条数最多。

  都是使用一个全局变量,在后续遍历二叉树的过程中,记录给定二叉树的所有子树的 最大路径和/边数最多的

路径边数。

代码和注释如下:

 1 class Solution {
 2 public:
 3     int diameterOfBinaryTree(TreeNode* root)
 4     {
 5         res = 0;
 6         int tmp = diameterOfBinaryTreeHlper(root);
 7         return res;
 8     }
 9 
10     int diameterOfBinaryTreeHlper(TreeNode* root)
11     {
12         if(root == NULL ) return 0;
13         int left = diameterOfBinaryTreeHlper(root->left);
14         int right = diameterOfBinaryTreeHlper(root->right);
15         int tree_depth = root->left == NULL && root->right == NULL ?0: max(left,right) + 1;
16         int left_depth = root->left == NULL?0:left+1;
17         int right_depth = root->right == NULL?0:right+1;
18         res = max(res,left_depth + right_depth);
19         return tree_depth;
20     }
21 private:
22     int res;
23 };
原文地址:https://www.cnblogs.com/wangxf2019/p/13992089.html