[Leetcode] Sum Root to Leaf Numbers
来源:互联网 发布:java字符串数组长度 编辑:程序博客网 时间:2024/05/22 12:58
题目:
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
.
要求计算每条路径得到的数字之和,发现跟遍历二叉树很类似,每当到达叶节点时记录当前路径上的值。
vector<int> res;void sumNumbers(TreeNode *x, int n){n=n*10+ x->val; //转换路径上经过的数字if(x->left)sumNumbers(x->left, n); //递归遍历if(x->right)sumNumbers(x->right, n);if(x->left==NULL && x->right==NULL) //只有到叶节点时才保存res.push_back(n);}int sumNumbers(TreeNode *root){ int sum=0; if(root ==NULL) return sum; sumNumbers(root,0); for(int i=0; i<res.size(); i++) sum+=res[i]; return sum;}
0 0
- leetcode 86: Sum Root to Leaf Numbers
- [LeetCode] Sum root to leaf numbers
- LeetCode : Sum Root to Leaf Numbers
- [leetcode] Sum Root to Leaf Numbers
- 【leetcode】Sum Root to Leaf Numbers
- LeetCode之sum root to leaf numbers
- leetcode:Sum Root to Leaf Numbers
- [LeetCode]Sum Root to Leaf Numbers
- [Leetcode]Sum Root to Leaf Numbers
- [leetcode]Sum Root to Leaf Numbers
- leetcode Sum Root to Leaf Numbers
- LeetCode-Sum Root to Leaf Numbers
- [leetcode] Sum Root to Leaf Numbers
- LeetCode 129: Sum Root to Leaf Numbers
- LeetCode - Sum Root to Leaf Numbers
- leetcode之Sum Root to Leaf Numbers
- LeetCode | Sum Root to Leaf Numbers
- LeetCode - Sum Root to Leaf Numbers
- spring mvc 拦截器配置
- RAII的一些实现
- Java多线程编程总结
- unable to load default svn client 和 Eclipse SVN 插件与TortoiseSVN对应关系
- 线性表的链式表示和实现
- [Leetcode] Sum Root to Leaf Numbers
- 在eclipse中设计BPMN 2.0工作流定义的基本步骤
- 生个女儿蘑菇高仿机废话价格等级吗
- 【索引】Maths - Number Theory
- 相邻字符串常量将会自动合并成一个字符串
- java ReentrantLock与synchronized详细分析与例子详解
- android 下拉刷新上拉加载更多,高仿ios左滑动删除item,解决了众多手势问题
- LinkedHashMap的实现原理
- 发给价格的健康放寒假发给减肥好