题目:
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
.
这道题使用递归来解决非常优雅,代码也简洁明了。
我是在LeetCode OJ上提交了自己的代码,Accepted后才看该题的Discuss的。看到很多人使用的方法跟我的一样(额...,应该说我的跟很多人的一样。)
下面给出我自己的代码,为了测试的方便,我也写了使用前序创建二叉树的代码。
#include <iostream>
using namespace std;
//Definition for binary tree
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
// 使用前序遍历来创建二叉树
void createBinaryTree(TreeNode **T)
{
int val;
cin >> val;
// 由于每个节点的值都是0-9,所以就用-1表示空节点
if(val == -1)
*T = NULL;
else
{
*T = new TreeNode(val);
if(*T == NULL)
{
cout << "out of space!" << endl;
return;
}
createBinaryTree(&(*T)->left);
createBinaryTree(&(*T)->right);
}
}
// 核心递归算法
void calculateSum(TreeNode *root, int currentNum, int &sum)
{
//
if( root == NULL )
return;
currentNum = currentNum * 10 + root->val;
// 叶子节点
if ( root->left == NULL && root->right == NULL )
{
sum += currentNum;
return;
}
// 遍历左子树
calculateSum(root->left, currentNum, sum);
// 遍历右子树
calculateSum(root->right, currentNum, sum);
}
int sumNumbers(TreeNode *root)
{
if(root == NULL)
return 0;
int sum = 0;
calculateSum(root, 0, sum);
return sum;
}
int _tmain(int argc, _TCHAR* argv[])
{
TreeNode *bTree;
createBinaryTree(&bTree);
int sum = sumNumbers(bTree);
cout << "Sum : " << sum << endl;
return 0;
}
例如题目中的树,前序创建时输入: 1, 2, -1, -1, 3, -1, -1
输出结果为: Sum : 25