[LeetCode]Sum Root to Leaf Numbers
2015-12-20 11:32
176 查看
题目描述:(链接)
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 =
解题思路:
深度优先搜索,遍历所有根节点到叶节点的路径。
Given a binary tree containing digits from
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) { return sumNumbers(root, 0); } private: int sumNumbers(TreeNode *root, int sum) { if (root == nullptr) return 0; sum = sum * 10 + root->val; if (root->left == nullptr && root->right == nullptr) { return sum; } return sumNumbers(root->left, sum) + sumNumbers(root->right, sum); } };
相关文章推荐
- 关于优酷视频上传失败或暂停之后一直处于上传中或者处理中删除不掉的解决方法
- js整体介绍
- git常用命令
- js弹出新窗口的6中方法
- MatLab Kmeans聚类
- lcd调色板工作原理详解
- swift和storyborad环境下通过xib自定义TableViewCell
- 【杭电】[2007]平方和与立方和
- Oracle数据库闪回FLASHBACK命令总结
- 6大Container OS介绍
- Maven 配置环境
- 设计模式(十六)---观察者模式
- 浅论带有敏感词网站的优化策略
- 软件调试读书笔记
- createNewFile()与createTempFile()的区别
- 2.手机竖直方向实现循环切换页面
- 实战数组,for循环 if语句 switch语句 制作一个小明的成绩管理系统
- java——多线程的实现
- JSP基础篇
- MYSQL外键(Foreign Key)的使用