2022年11月29日 星期二

[559] Maximum Depth of N-ary Tree

雖然有覺得可以用自己一個遞迴就寫出來,但還是卡卡的,用了一個current 去多存目前的深度;
int childDep(struct Node* root, int curDep) {
int max=curDep;
int tmp=0;
for (int i=0;i<root->numChildren;i++)
{
tmp = childDep(root->children[i],curDep+1);
if (tmp > max)
max=tmp;
}
return max;
}

int maxDepth(struct Node* root) {
if (root==NULL)
return NULL;
int currentDep=1;
int ret=1;
for (int i=0;i<root->numChildren;i++)
{
int tmp=childDep(root->children[i],currentDep+1);
if (tmp > ret)
ret = tmp;
}
return ret;
}

果然後來看別人寫,這樣就可以了 ?!再多想兩分鐘?! XDDDDD

int maxDepth(struct Node* root) {
if (root==NULL)
return NULL;
int ret=0;
for (int i=0;i<root->numChildren;i++)
{
int tmp=maxDepth(root->children[i]);
if (tmp > ret)
ret = tmp;
}
return ret+1;
}

沒有留言:

張貼留言