543. 二叉樹的直徑 Diameter of Binary Tree

題目 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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章