結果完全弄反XD 不需要傳的是count XD 就一層一層算,return 時往回相加就是了...
我真沒有慧根(痛哭)
int check(struct TreeNode* root, int curMax)
{
int gnodes=0;
if (root == NULL)
return gnodes;
if (root->val >= curMax)
{
curMax = root->val;
gnodes++;
}
return gnodes+check(root ->left, curMax)+ check(root ->right, curMax);
}
int goodNodes(struct TreeNode* root){
return check(root, root->val);
}
(照例一開始的版本放最後。) 因為跑完左child 時curMax 已經用不到了,右child curMax 會是它的parant,所以這樣寫的話check return void 就可以了。
(然後就可以引申成上面的寫法!)L
void check(struct TreeNode* root,int curMax , int *count)
{
if (root == NULL)
return;
if (root->val >= curMax)
{
curMax = root->val;
(*count)++;
}
check(root ->left, curMax , count);
check(root ->right, curMax , count);
return;
}
int goodNodes(struct TreeNode* root){
int count= 0;
check(root,root->val , &count);
return count;
}
沒有留言:
張貼留言