129. Sum Root to Leaf Numbers
来源:互联网 发布:centos开启3306端口 编辑:程序博客网 时间:2024/06/10 08:20
problem:
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
.
solution:
class Solution {
public:
int i = 0;
int sumNumbers(TreeNode* root) {
if (root == NULL) return 0;
return sum(root, 0);
}
int sum(TreeNode * root, int val)
{
if (root->left == NULL && root->right == NULL) return (val * 10 + root->val);
if (root->left != NULL && root->right == NULL) return sum(root->left, val * 10 + root->val);
if (root->left == NULL && root->right != NULL) return sum(root->right, val * 10 + root->val);
if (root->left != NULL && root->right != NULL)
return sum(root->left, val * 10 + root->val) + sum(root->right, val * 10 + root->val);
}
};
- [LeetCode]129.Sum Root to Leaf Numbers
- LeetCode 129. Sum Root to Leaf Numbers
- [leetcode] 129.Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 【leetcode】129. Sum Root to Leaf Numbers
- [leetcode] 129. Sum Root to Leaf Numbers
- [LeetCode]129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers LeetCode
- [LeetCode]129. Sum Root to Leaf Numbers
- leetcode 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- Leetcode 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- LeetCode *** 129. Sum Root to Leaf Numbers
- LeetCode-129.Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- 129. Sum Root to Leaf Numbers
- Activity的四大启动模式总结
- Android使用SVG矢量图打造酷炫动画效果
- Gradle下载与环境变量配置
- scikit-learn 中文文档-集成方法-监督学习|ApacheCN
- C++进阶—>Socket通信那点事
- 129. Sum Root to Leaf Numbers
- Spring BeanDefinition及读取、注册
- LeetCode.232 Implement Queue using Stacks
- 刷新HorizontalScrollView
- 《算法竞赛入门经典》第十章 数学概念与方法 UVa11582(幂取模,循环规律,模算术)
- 前端学习 | 使用webpack构建React项目
- tomcat7之添加管理员账户
- Fragment学习
- Android四大组件之广播总结