129. Sum Root to Leaf Numbers
problem description
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.
algorithm thought
树问题,递归解决,这里需要到叶子节点才能知道最后的值是多少。需要将父节点的信息传入子节点。这里有两种方法传递一种是直接改变节点的值,父节点改将自己的值加到子节点。还有一种方法是用参数传递。
code
//改变叶子节点的值
/**
* 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:
int res=0;
int sumNumbers(TreeNode* root) {
if(root!=NULL)
sumNumber(root);
return res;
}
void sumNumber(TreeNode* root){
if(root->left){
root->left->val+=root->val*10;
sumNumber(root->left);
}
if(root->right){
root->right->val+=root->val*10;
sumNumber(root->right);
}
if(root->left==NULL&&root->right==NULL)
res+=root->val;
}
};
//用参数传递
class Solution {
public:
int res=0;
int sumNumbers(TreeNode* root) {
if(root==NULL)
return 0;
helper(root,0);
return res;
}
void helper(TreeNode* root,int add){
if(root->left==NULL&&root->right==NULL){
res+=(add*10+root->val);
return;
}
if(root->left)
helper(root->left,add*10+root->val);
if(root->right)
helper(root->right,add*10+root->val);
}
};
algorithm analysis
两个代码时间复杂度分析,可能大家都认为第一个算法更好。但是运行下来,反而是第二个代码更快,我认为是第一个代码修改了指针中的值,修改值可能比读取一个值消耗的时间多很多,导致用第二个代码传参数更好。
Last updated