Sum root to leaf numers:I get wrong answer but i think it works fine.


  • 0
    G

    I get WA for the following input :

    Input:	[1,null,5]
    Output:	6
    Expected:15
    

    But when i run it on my machine and when i dry run it, the program outputs 15.What am i missing here.
    I hope i am interpreting the tree right.Correct me if the following tree does not represent the input

      1
        \
         5
    

    here is my code

    int digits(int n)
        {
            int count=0;if(n==0)return 1;
            while(n>0)
            {
                n/=10;
                count++;
            }
        }
        int sumNumbers(TreeNode* root)
        {
            if(root==NULL)
            return 0;
            if(root->left==NULL && root->right==NULL)
            return root->val;
            int temp=root->val;
            int temp2=root->val;
            if(root->left==NULL)
            temp=0;
            else
            {
                int p=sumNumbers(root->left);
                temp=temp*pow(10,digits(p))+p;
            }
            if(root->right==NULL)
            temp2=0;
            else
            {
                int q=sumNumbers(root->right);
                temp2=temp2*pow(10,digits(q))+q;
            }
            return (temp+temp2);
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.