簡體   English   中英

深度優先和樹遍歷問題 c

[英]Problem with Depth First & Tree Traversals in c

我在 C 編程中遇到與 dfs 相關的問題。 我需要找到等於子樹平均值的計數節點。 不幸的是,我在 c 上沒有找到足夠的指南,所以我正在尋求幫助。 此代碼仍然無法正常工作並給出錯誤的結果,所以如果您能指出我的錯誤,我將不勝感激。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     struct TreeNode *left;
 *     struct TreeNode *right;
 * };
 */
int ans=0;
int dfs(struct TreeNode* root){
    if (root == NULL) return 0,0;
    int left,left_count = dfs(root->left);
    int right,right_count = dfs(root->right);
    int totalSum = left+right+root->val;
    int count = left_count + right_count + 1;
    if (totalSum/count == root->val) ans++;
    return totalSum,count;
}

int averageOfSubtree(struct TreeNode* root){
    dfs(root);
    return ans;
}

我已經多次修改這段代碼,但我從來沒有得到一個有效的代碼。 在 output,我得到了數據,但它不正確(提前致謝)。

一些問題:

  • 您似乎打算讓您的dfs function 返回兩個int值,但事實並非如此。 您的 function 被聲明為返回int (一),並且逗號運算符不會返回元組(就像在 Python 中一樣),但會計算第二個參數。

    所以return 0,0; return 0;

    return totalSum,count; return count;

    int left,left_count = dfs(root->left); 不會初始化left ,只會初始化left_count

    的確,您需要將計數和總和都提供給調用者,並且有幾種方法可以做到這一點。 一種是將指向int變量的指針作為 arguments 傳遞給dfs

  • 由於ans是全局的,並且不會重置為 0,因此 Leet Code 上的測試會將先前運行的結果累積到當前運行中。 最好一起避免使用全局變量。 相反,您可以使它成為dfs的返回值。 或者還有一個指向作為參數傳遞的變量的指針......

更正版本:

int dfs(struct TreeNode* root, int *count, int *sum){
    if (root == NULL) {
        *count = *sum = 0;
        return 0;
    }
    int left, left_count, right, right_count;
    int ans = dfs(root->left, &left_count, &left) + dfs(root->right, &right_count, &right);
    *sum = left + right + root->val;
    *count = left_count + right_count + 1;
    return ans + (*sum/(*count) == root->val);
}

int averageOfSubtree(struct TreeNode* root){
    int sum, count; // Dummy
    return dfs(root, &sum, &count);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM