https://leetcode-cn.com/problems/diameter-of-binary-tree/
给定一棵二叉树,你需要计算它的直径长度。一棵二叉树的直径长度是任意两个结点路径长度中的最大值。这条路径可能穿过根结点。
示例 :
给定二叉树
1
/ \
2 3
/ \
4 5
返回 3, 它的长度是路径 [4,2,1,3] 或者 [5,2,1,3]。
注意:两结点之间的路径长度是以它们之间边的数目表示。
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
/*思路:
最大直径由任意节点左子树的最大深度+该节点右子树的最大深度,即该题为求二叉树中某个节点的最大左右子树深度之和
两层递归?
*/
int count_depth_node(struct TreeNode* root){
if(!root) return 0;
int l = 1 + count_depth_node(root->left);
int r = 1 + count_depth_node(root->right);
return (l > r) ? l : r;
}
int forecah_depth(struct TreeNode* root, int *max){
if(!root) return 0;
int cur = count_depth_node(root);
int l = forecah_depth(root->left, max);
int r = forecah_depth(root->right, max);
*max = (l + r) > *max ? (l + r) : *max;
return cur;
}
int diameterOfBinaryTree(struct TreeNode* root){
int max = 0;
forecah_depth(root, &max);
return max;
}