sum-root-to-leaf-numbers
来源:互联网 发布:青岛华为软件开发 编辑:程序博客网 时间:2024/06/05 08:27
sum-root-to-leaf-numbers
题目描述
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1 / \ 2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.Return the sum = 12 + 13 =25.
思想
主要是树的遍历,dfs
这也考察了递归遍历时的处理
代码
class Solution {public: int sumNumbers(TreeNode *root) { if(root == NULL) return 0; int res = 0, s = 0; dfs(root, res, s); return res; } void dfs(TreeNode *root, int &res, int s) { s += root->val; if(root->left != NULL) { s = s * 10; dfs(root->left, res, s); s = s / 10; } if(root->right != NULL) { s = s * 10; dfs(root->right, res, s); s = s / 10; } if(root->left == NULL && root->right == NULL) { res += s; } return; }};
阅读全文
0 0
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- Sum Root to Leaf Numbers
- IPC详解
- 【Android_View】ImageView源码简析笔记(五)
- js 遇到的坑clear
- 【JAVA】数据交换,java方法参数
- Is It A Tree? -- HDOJ
- sum-root-to-leaf-numbers
- mysql
- win10装ubuntu双系统启动时卡在命令行
- css实现鼠标悬停图片放大显示
- 由日期转换成星期几
- Yii2 Layout 传值实现和原理
- c语言typedef的用法
- 卫星热分析-论文有感
- Android 6.0 ScrollView嵌套RecyclerView高度自适应问题