今天一大早脖子痛难受的一笔,感觉应该是着凉的缘故,但题还是得照常刷,下面就和大家分享一下经验吧!
题目如下:
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.
Note: A leaf is a node with no children.
Example:
Input: [1,2,3]
1
/ \
2 3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:
Input: [4,9,0,5,1]
4
/ \
9 0
/ \
5 1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.
题意分析:
给定一个仅包含数字0-9的二叉树,每个从根节点到叶子节点的路径代表一个数,请求得所有路径代表的数之和。
方法一(递归法)
与“https://blog.csdn.net/Vensmallzeng/article/details/95324164”中的方法一基本一样,但该方法的时间复杂度、空间复杂度都是不尽人意的。
解题代码如下:
class Solution{
public:
int sumNumbers(TreeNode* root){
vector<vector<int>> temp;
int res = 0;
temp = sumNumbers_son(root);
for (int i = 0; i < temp.size(); i++) {
int total = 0;
for (int j = 0; j < temp[i].size(); j++) {
total += temp[i][j]*pow(10,j);
}
res += total;
}
return res;
}
vector<vector<int>> sumNumbers_son(TreeNode* root){
vector<vector<int>> res;
if(root == NULL) return res;
if(root->left == NULL && root->right == NULL) {res.push_back({root->val}); return res;}
vector<vector<int>> leftpath = sumNumbers_son(root->left);
for (int i = 0; i < leftpath.size(); i++) {leftpath[i].push_back(root->val); res.push_back(leftpath[i]);}
vector<vector<int>> rightpath = sumNumbers_son(root->right);
for (int i = 0; i < rightpath.size(); i++) {rightpath[i].push_back(root->val); res.push_back(rightpath[i]);}
return res;
}
};
提交后的结果如下:
方法二(递归法)
本题并不是简单的把各个节点值相加,而是每当遇到一个新子结点时,要把其父结点的值扩大10倍之后再与其值相加。若遍历到叶子结点,则将当前的累加结果sum返回,否则需对其左右子结点分别进行递归调用,最后将两部分结果相加即为所求之和。
解题代码如下:
class Solution{
public:
int sumNumbers(TreeNode* root){
return sumNumbers_son(root, 0);
}
int sumNumbers_son(TreeNode* root, int sum){
if(root == NULL) return 0;
sum = sum*10 + root->val;
if(root->right == NULL && root->left == NULL) return sum;
return sumNumbers_son(root->right, sum) + sumNumbers_son(root->left, sum);
}
};
提交后的结果如下:
日积月累,与君共进,增增小结,未完待续。