LeetCode:Sum Root to Leaf Numbers
2015-09-06 19:51
363 查看
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 =
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.
/** * 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) { int sum=0; return dfs(root,sum); } int dfs(TreeNode *root,int sum) { if(root==NULL) 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); } };
相关文章推荐
- unity之射线
- 标题:利用动态规划求解最优二叉树
- vs2010 mpi并行环境配置编译
- 软件测试基础_对应Mantis整理的测试计划流程步骤
- hdu5168 Legal path DP,最短路
- Asp.Net 之 WebService部署到服务器后出现" The test form is only available for requests from the local machine "
- bzoj3669
- CSS从图标集里截取某一图标
- 0906学习记录
- 尝试实现 atoi和atof函数
- 原生JS实现瀑布流
- bzoj3669
- 写html文件一定要养成好习惯
- UI课程04 事件处理
- Android常用控件之碎片Fragment
- LeetCode -- 4Sum
- HTML5八大特性助力移动WebApp开发
- 求两个字符串相互交叉出现
- Android开发中的问题及相应解决(持续更新)
- CCS3的transform--rotate的使用顺序