543.二叉树的直径
我以为最长路径是必须要经过根结点的,结果我错了。
这样就需要让左右子树的最大深度相加得到路径。
depth求一个树的深度,
主函数求一个结点的最大直径并更新。
int depth(struct TreeNode*root){
if(root==NULL)
return 0;
int ans=0;
int L=depth(root->left);
int R=depth(root->right);
ans=1+fmax(L,R);
return ans;
}
int diameterOfBinaryTree(struct TreeNode* root){
if(root==NULL)
return 0;
int cnt=depth(root->left)+depth(root->right);
cnt=fmax(diameterOfBinaryTree(root->left),cnt);
cnt=fmax(diameterOfBinaryTree(root->right),cnt);
return cnt;
}
654.最大二叉树
虽然是中等题,但我花了一些时间做出来了,一开始没有思路,慢慢磨就把思路磨出来了🌝🌝
g是用来返回数组中最大值的下标。比之前的题简单一丢丢丢,之前几道题都是递归函数调用递归函数。
int g(int *nums,int numsSize){
int max=0,i=0;
for(i=0;i<numsSize;i++)
max=fmax(max,nums[i]);
for(i=0;i<numsSize;i++)
if(nums[i]==max)
//printf("%d",i);
return i;
return 0;
}
struct TreeNode* constructMaximumBinaryTree(int* nums, int numsSize){
if(numsSize==0)
return 0;
struct TreeNode*root=(struct TreeNode*)malloc(sizeof(struct TreeNode));
root->val=nums[g(nums,numsSize)];
printf("%d ",root->val);
root->left=constructMaximumBinaryTree(nums,g(nums,numsSize));
root->right=constructMaximumBinaryTree(nums+g(nums,numsSize)+1,numsSize-g(nums,numsSize)-1);
return root;
}