LeetCode(129) Sum Root to Leaf Numbers
2015-11-12 13:30
411 查看
题目
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,
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.
分析
按照二叉树的深度遍历,累计所有路径组成整数的和。使用二叉树的递归深度优先遍历实现!
AC代码
/** * 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 ret = 0; if (!root) return ret; else if (!root->left && !root->right) { ret = root->val; return ret; } else dfs(root, root->val , ret); return ret; } //深度优先遍历,得到所有根节点到叶子节点的路径和 void dfs(TreeNode *root, int val, int &sum) { if (!root->left && !root->right) sum += val; if (root->left) { dfs(root->left, val * 10 + root->left->val, sum); } if (root->right) { dfs(root->right, val * 10 + root->right->val, sum); } } };
GitHub测试程序源码
相关文章推荐
- android某加固脱壳(一)
- LeetCode(129) Sum Root to Leaf Numbers
- 平台顺利通过公安部一所《GBT 28181-2011 安全防范视频监控联网系统信息传输、交换、控制技术要求》检测
- Bozosort: Sorting by Exchanging
- 一句shell命令搞定代码行数统计
- soj 3014: Seek the Name, Seek the Fame (字符串hash)
- Ubuntu下自己编译安装和卸载软件
- Theaon:theaon的图结构
- spring+hibernate工程使用JNDI连接部署至websphere,报错Caused by: java.lang.ClassNotFoundException: oracle.sql.BLO
- Robot FrameworkResource及关键字的使用
- STM32 FOC SDK 上电电机自动旋转
- android Butter Knife 使用详解
- 在Eclipse中修改Jsp页面的新增模板
- 安装分布式文件系统MooseFS
- 整数划分问题
- 房地产O2O应用中为什么很少提供社交入口?
- 结构体内存分配问题
- HBase基本数据操作详解【完整版,绝对精品】
- 图像处理中的数学原理详解11——线性空间
- Robot Framework使用For循环