Sum Root to Leaf Numbers
来源:互联网 发布:淘宝怎么装修手机店铺 编辑:程序博客网 时间:2024/06/05 00:09
LeetCode Sum Root to Leaf Numbers
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,
1 / \ 2 3
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
.
深度优先搜索:
//将动态数组中的单个数数转换成整数int vecToInt(vector<int>& v){int sum = 0;for(int i=0; i<v.size(); i++){sum += (pow(10, v.size()-1-i)*v[i]);}return sum;}void pathSum(TreeNode* p, vector<int>& sub_sum, int & sum){//如果是叶节点,则计算出动态数组中的数字,计入sum中if(p->left==NULL && p->right==NULL){sub_sum.push_back(p->val);sum = sum + vecToInt(sub_sum);return ;}sub_sum.push_back(p->val);if(p->left!=NULL){pathSum(p->left, sub_sum, sum);sub_sum.pop_back();}if(p->right!=NULL){pathSum(p->right, sub_sum, sum);sub_sum.pop_back();}}int sumNumbers(TreeNode *root) {if(root==NULL)return 0;vector<int> sub_sum;int sum = 0;pathSum(root, sub_sum, sum);return sum;}
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
- 非接触式IC卡、条码卡、磁道卡、接触式IC卡、芯片卡
- java环境变量配置
- LeetCode OJ 之 Remove Element (删除指定元素)
- 23种设计模式之--简单工厂模式
- hdu1540 线段树区间合并
- Sum Root to Leaf Numbers
- HDU 4786(最小生成树 kruskal)
- 给予下列一串字符串a,b,c,ab,bb,cb,ac,bc,cc,aab,bab,cab,abb,bbb,cbb...通过编程实现以上字符串实现,并要求有相应字符串的位置信息,假设a的位置为0
- lower_bound()返回值
- QT常用知识
- Win8 下的android 环境的搭建
- gitcafe for Eclipse的环境配置
- redis复制
- 【struts2】拦截器的工作模拟实现