[Leetcode] [tree] [Sum root to leaf numbers]

Source: Internet
Author: User

A very simple question, similar to path sum.

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     void sum(TreeNode *root, int now, int &res) {13         if (root == NULL) {14             return;15         }16         now = now * 10 + root->val;17         if (root->left == NULL && root->right == NULL) {18             res += now;19         }20         sum(root->left, now, res);21         sum(root->right, now, res);22     }23     int sumNumbers(TreeNode *root) {24         int res = 0;25         sum(root, 0, res);26         return res;27     }28 };

However, after reading the problem solution, I found that the solution is better than my algorithm! Learn now!

 1 /** 2  * Definition for binary tree 3  * struct TreeNode { 4  *     int val; 5  *     TreeNode *left; 6  *     TreeNode *right; 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} 8  * }; 9  */10 class Solution {11 public:12     int sum(TreeNode *root, int now) {13         if (root == NULL) {14             return 0;15         }16         now = now * 10 + root->val;17         if (root->left == NULL && root->right == NULL) {18             return now;19         }20         return sum(root->left, now) + sum(root->right, now);21     }22     int sumNumbers(TreeNode *root) {23         return sum(root, 0);24     }25 };

Fewer parameters, shorter code!

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.