Skip to content

Commit

Permalink
Add 129 in c language
Browse files Browse the repository at this point in the history
  • Loading branch information
julienChemillier authored Oct 28, 2022
1 parent 98b6666 commit 66e61a4
Showing 1 changed file with 22 additions and 0 deletions.
22 changes: 22 additions & 0 deletions c/129-sum-root-to-leaf.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/*
Return the total sum of all root-to-leaf numbers.
Space: O(1)
Time: O(n)
*/

int dfs(struct TreeNode* r, int acc) {
if (r==NULL)
return acc;
if (r->left==NULL && r->right==NULL)
return acc*10 + r->val;
if (r->left==NULL)
return dfs(r->right, acc*10 + r->val);
if (r->right==NULL)
return dfs(r->left, acc*10 + r->val);
return dfs(r->right, acc*10 + r->val) + dfs(r->left, acc*10 + r->val);
}

int sumNumbers(struct TreeNode* root){
return dfs(root, 0);
}

0 comments on commit 66e61a4

Please sign in to comment.