題目 https://leetcode-cn.com/problems/diameter-of-binary-tree/submissions/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
#define max(a,b) ((a)>(b)?(a):(b))
int dia(struct TreeNode* root,int *sum){
if(root == NULL)
return 0;
int left = 0,right = 0;
if(root->left != NULL){
left = dia(root->left,sum);
}else
{
left = 0;
}
if(root->right != NULL){
right = dia(root->right,sum);
}else
{
right = 0;
}
if(root->left == NULL && root->right == NULL)
return 0;
if(root->left != NULL && root->right != NULL)
*sum = max(*sum,left+right+2);
return 1 + max(left,right);
}
int diameterOfBinaryTree(struct TreeNode* root){
int sum = 0;
int sum2;
sum2 = dia(root,&sum);
return max(sum,sum2);
}
路徑是三選一,左子樹->root->右子樹、左子樹->root->root.parent、右子樹->root->root.parent
1、root==NULL 0
2、root->left==NULL&&root->right==NULL 0
3、root->left!=NULL && root->right!=NULL 左子樹->root->右子樹
4、左子樹->root->root.parent、右子樹->root->root.parent