繁体   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