簡體   English   中英

二叉樹中左葉節點的總和

[英]sum of left leaf nodes in a binary tree

該解決方案向我展示了分割錯誤,盡管它對我嘗試過的所有樹木都適用。 誰能幫我檢測到錯誤。 碼:

    /*Structure of the node of the binary tree is as
    struct Node
    {
        int data;
        struct Node* left;
        struct Node* right;
    };
    */
    // function should return the sum of all 
    // left leaf nodes
    int sum=0,i=1;
    Node* h;
    int leftLeafSum(Node* root)
    {
        if(i==1)
        {
           h=root;
           i--;
        }
        Node* temp=root;
        if((temp->left!=NULL)&&(temp->left->left==NULL)&&   (temp->left->right==NULL))
           sum+=temp->left->data;
        if(temp->left!=NULL)
           leftLeafSum(temp->left);
        if(temp->right!=NULL)
           leftLeafSum(temp->right);
        if(temp==h)
        {
           i=1;
           int s=sum;
           sum=0;
           return s;
        }
    }

您需要檢查初始指針是否不等於NULL:

int leftLeafSum(Node* root)
{
    if (root==NULL)
        return 0;
    ...

當我添加此內容時,網站認為提交的內容是正確的。

暫無
暫無

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

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