LeetCode: Sum Root to Leaf Numbers [129]
2016-01-16 14:15
399 查看
【题目】
Given a binary tree containing digits from0-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.
【题意】
给定一棵二叉树,节点值仅仅可能是[0-9]区间上的值,每一条从根到叶子的节点都能够看成一个整数。现要求把全部路径表示的整数相加,返回和【思路】
DFS,找到左右的路径,实数化每条路径上组合数。将全部的路径上得到的整数求和。这里2有个问题:
1. 假设某条路径太长,组合数已经超出了int的上界怎么办
2. 假设终于的和超出了int的上界怎么办
题目没有进一步的说明,我们默认所给的測试用例都保证不会越界。
【代码】
/** * Definition for binary tree * struct TreeNode { * int val; * TreeNode *left; * TreeNode *right; * TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */ class Solution { public: void dfs(int&result, int num, TreeNode*node){ //result表示全部路径的组合 //num表示根到node的父节点的组合数 if(node){ num=10*num+node->val; //计算从根到当前节点的组合数 if(node->left==NULL && node->right==NULL){ result+=num; //已经找到一个条路径的组合数,累加到result上 return; } if(node->left) dfs(result, num, node->left); if(node->right) dfs(result, num, node->right); } } int sumNumbers(TreeNode *root){ if(root==NULL)return NULL; int result=0; int num=0; dfs(result, num, root); return result; } };
相关文章推荐
- SQL SERVER示例:修改自定义数据类型精度
- 二级菜单栏
- 设置UITabBar按钮的颜色
- SQL SERVER分页存储过程
- 电脑对外开放端口
- 手动编译安装mysql,报错没有libaio模块,
- iOS-项目中的文件
- lightoj 1013 - Love Calculator
- sqlserver2008 存储过程使用表参数
- static静态、单例设计模式
- 一个简单聊天界面的UI实现
- SQL SERVER 小技巧
- UVA 719 / POJ 1509 Glass Beads (最小表示法/后缀自动机)
- SQL Server中调用WebService的实例
- iOS UILable自适应高度
- Delphi简单的数据操作类
- 后缀自动机学习总结
- convertToNodeSpace等Cocos2dx中坐标系转换解析
- 算法笔记——【分治法】合并排序
- Delphi DBGrid实现多选