LeetCode 129:Sum Root to Leaf Numbers
2015-12-31 14:30
465 查看
Given a binary tree containing digits from
a number.
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 =
Subscribe to see which companies asked this question
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.
Subscribe to see which companies asked this question
class Solution { public: int sumNumbers(TreeNode* root) { return dfs(root, 0); } int dfs(TreeNode* root, int sum){ if (root == 0) return 0; if (root->left == NULL && root->right == NULL) { return sum * 10 + root->val; } return dfs(root->left, sum * 10 + root->val) + dfs(root->right, sum * 10 + root->val); } };
#include<iostream>
#include<new>
#include<vector>
using namespace std;
//Definition for binary tree
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 dfs(root, 0); } int dfs(TreeNode* root, int sum){ if (root == 0) return 0; if (root->left == NULL && root->right == NULL) { return sum * 10 + root->val; } return dfs(root->left, sum * 10 + root->val) + dfs(root->right, sum * 10 + root->val); } };
void createTree(TreeNode *&root)
{
int i;
cin >> i;
if (i != 0)
{
root = new TreeNode(i);
if (root == NULL)
return;
createTree(root->left);
createTree(root->right);
}
}
int main()
{
Solution s;
TreeNode *root;
createTree(root);
int path = s.sumNumbers(root);
cout << path <<endl;
system("pause");
return 0;
}
相关文章推荐
- Apache和Nginx运行原理解析
- ios 程序判断是否第一次启动
- 装饰模式
- 欢迎使用CSDN-markdown编辑器
- [leetcode]Inorder Successor in BST
- SpringFramework对ibatis的支持
- Bus Hound简介(2)
- MongoDB学习笔记八:复制
- sed、grep
- Spring概述
- Android Studio 快捷键
- 输出整数的所有划分
- Spring概述
- MongoDB学习笔记七:管理
- 抓包工具: WireShark; Fiddler; Charles
- ASP.NET MVC html help
- 二维码扫描利用ZBar实现
- Win10开发:Toast通知之应用激活
- 二进制和十六进制互转
- 卡尔曼滤波器跟踪