题目描述:
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.
分析:
此题其实是考察二叉树的深度优先遍历。要将根节点到每一个叶子节点的路径所得到的整数相加,那么用递归思路实现起来比用迭代简单很多。
递归思路:
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.
分析:
此题其实是考察二叉树的深度优先遍历。要将根节点到每一个叶子节点的路径所得到的整数相加,那么用递归思路实现起来比用迭代简单很多。
递归思路:
每次处理一个节点时都是在该节点之前遍历的节点所构成的整数的基础上。如果当前节点为空,直接返回;如果当前的节点不为空但是左右节点均为空(即当前节点为叶子节点),那么将该节点加入到整数的构成,就完成了一条路径的搜索,将该条路径组成的整数累加到全局和中,然后递归处理它的左右孩子节点即可。
/**///0ms*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
/**
* befSum 是处理node之前的该条路径所组成的整数
* res 是所求
* node 是当前即将要处理的节点
*/
void getSum(TreeNode *node, int befNum,int &res){
if(node == NULL)
return;
int curNum = befNum*10 + node->val;
if(!node->left && !node->right){ //node为叶子节点,将该条路径的整数累加到res中
res += curNum;
return;
}
getSum(node->left,curNum,res); //递归处理左右孩子节点,将和累加到res中
getSum(node->right,curNum,res);
}
int sumNumbers(TreeNode* root) {
int res = 0;
if(root == NULL)
return res;
getSum(root,0,res);
return res;
}
};