LeetCode - Sum Root to Leaf Numbers

Sum Root to Leaf Numbers

2014.1.1 19:55

Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path 1->2->3 which represents the number 123.

Find the total sum of all root-to-leaf numbers.

For example,

    1
   / \
  2   3

The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.

Return the sum = 12 + 13 = 25.

Solution:

  The solution is plain, traverse the tree and add up the numbers at leaf nodes.

  1->2->3 forms "123", that's (1 * 10 + 2) * 10 + 3. Then you know how the recursion is done.

  Time and space complexities are both O(n), where n is the number of nodes in the tree. The space complexity comes from the local paramater in recursive calls.

Accepted code:

 1 //1CE, 2WA, 1AC
 2 /**
 3  * Definition for binary tree
 4  * struct TreeNode {
 5  *     int val;
 6  *     TreeNode *left;
 7  *     TreeNode *right;
 8  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 9  * };
10  */
11 class Solution {
12 public:
13     int sumNumbers(TreeNode *root) {
14         // IMPORTANT: Please reset any member data you declared, as
15         // the same Solution instance will be reused for each test case.
16         
17         if(root == nullptr){
18             return 0;
19         }
20         
21         result = 0;
22         traverse(root, root->val);
23         
24         return result;
25     }
26 private:
27     int result;
28     void traverse(TreeNode *root, int weight) {
29         // Which level should 'weight' represent, vague...
30         // That's why you got two WAs here!!!
31         if(root == nullptr){
32             return;
33         }
34         
35         if(root->left == nullptr && root->right == nullptr){
36             result += weight;
37             return;
38         }
39         
40         if(root->left != nullptr){
41             traverse(root->left, weight * 10 + root->left->val);
42         }
43         if(root->right != nullptr){
44             traverse(root->right, weight * 10 + root->right->val);
45         }
46     }
47 };

 

转载于:https://www.cnblogs.com/zhuli19901106/p/3517980.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值