随笔- 509  文章- 0  评论- 151  阅读- 22万 

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 };
复制代码

 

 posted on   zhuli19901106  阅读(149)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· .NET10 - 预览版1新功能体验(一)
点击右上角即可分享
微信分享提示