2023年7月31日 星期一

[1161] Maximum Level Sum of a Binary Tree

嗯 ?! 有點說不上來哪裡怪怪的 XD
覺得應該要用recursive 解
又覺得level order traverse 好麻煩  XD
最後用了queue的概念,每一層push進去,計算該層的sum 並計錄下一層有幾個
然後前後位移queue的index (因為用C 寫 first in first out 的queue 太麻煩了XD 這算是一個偷吃步吧而且有隱含的bug?!  嗎)
最後就是這樣了.....(是哪樣XD)
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* struct TreeNode *left;
* struct TreeNode *right;
* };
*/
int maxLevelSum(struct TreeNode* root){
struct TreeNode** queue = malloc (sizeof (struct TreeNode*)*10000);
int count=0,level =1, start=0,end=1;
queue[count++]=root;
int sum= root->val;
int max=INT_MIN;
int small_leve=1;
count = (end-start);

while (count>0)
{
sum=0;
for (int i=0;i<count;i++)
{
if (queue[i+start]->left != NULL)
queue[end++]=queue[i+start]->left;

if (queue[i+start]->right != NULL)
queue[end++]=queue[i+start]->right;

sum += queue[i+start]->val;
}

if (sum > max)
{
small_leve=level;
max=sum;
}
start +=count;
count = (end-start);
level++;

}
free(queue);
return small_leve;

}

沒有留言:

張貼留言