Sum Root to Leaf Numbers
2015-08-02 21:35
246 查看
Given a binary tree containing digits from
An example is the root-to-leaf path
Find the total sum of all root-to-leaf numbers.
For example,
The root-to-leaf path
The root-to-leaf path
Return the sum = 12 + 13 =
Analyse: DFS. Compute the left and right subtree of the root respectively and add them.
Runtime: 4ms.
0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path
1->2->3which 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->2represents the number
12.
The root-to-leaf path
1->3represents the number
13.
Return the sum = 12 + 13 =
25.
Analyse: DFS. Compute the left and right subtree of the root respectively and add them.
Runtime: 4ms.
/** * Definition for a binary tree node. * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: int sumNumbers(TreeNode* root) { return dfs(root, 0); } int dfs(TreeNode* root, int sum){ if(!root) return 0; if(!root->left && !root->right) return sum * 10 + root->val; return dfs(root->left, sum * 10 + root->val) + dfs(root->right, sum * 10 + root->val); } };
相关文章推荐
- IOS NavigationBar 背景色
- 吐槽下 一个多月的实验
- 收集的55个Linux系统管理中常用的一些shell命令
- css系列-间隔与间距实例
- bower failed: UNABLE_TO_VERIFY_LEAF_SIGNATURE
- Category,protocol,Block总结对比
- esxi的时间同步问题
- 使用Jedis无法访问Redis的问题
- HDU1570水题
- 《C++游戏开发》笔记十二 战争迷雾:初步实现
- sublime安装AngularJS插件
- 70. Climbing Stairs
- C语言:通过函数指针来完成两个数的加减乘除(函数指针当做参数使用)
- sublime安装AngularJS插件
- 浅谈UIViewController生命周期
- CodeForces 295A Greg and Array(线段树)
- uva11044
- POJ 3414 Pots BFS
- 《编程之美》买书问题及c语言代码实现
- Maven 安装以及一些开发技巧