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
.
解题思路:
一个二叉树节点值是由0~9数字组成的,由根节点到每个叶子节点都组成一个整形数,根节点在最高位,叶子节点在最低位。现在求将这些所有整形数相加在一起的值。
方法一:
最直观的方法就是横向遍历该二叉树,并且将每个节点的值设置成母节点*10+该节点val。最后我们只要将叶子节点的val值相加即可。代码如下:
/**
* 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 sumNumbers(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return root->val;
int sum=0;
TreeNode* r=root;
deque<TreeNode* > st;
st.push_back(r);
deque<TreeNode* >st1;
while(!st.empty())
{
TreeNode* node=st.front();
st.pop_front();
if(node->left)
{
node->left->val+=node->val*10;
st1.push_back(node->left);
if(node->left->left==NULL&&node->left->right==NULL)
sum+=node->left->val;
}
if(node->right)
{
node->right->val+=node->val*10;
st1.push_back(node->right);
if(node->right->left==NULL&&node->right->right==NULL)
sum+=node->right->val;
}
if(st.empty())
{
st=st1;
st1.clear();
}
}
return sum;
}
};
方法二:
使用递归,int sumval(TreeNode* root,int c) 其中root指树中的一个节点,c指的是此节点的母节点的val值。返回由此节点到叶子节点的sum值。
class Solution {
public:
int sumval(TreeNode* root,int c)
{
int val=0;
if(root->left==NULL&&root->right==NULL)
return c*10+root->val;
if(root->left!=NULL)
val+=sumval(root->left,c*10+root->val);
if(root->right!=NULL)
val+=sumval(root->right,c*10+root->val);
return val;
}
int sumNumbers(TreeNode* root) {
if(root==NULL) return 0;
if(root->left==NULL&&root->right==NULL) return root->val;
return sumval(root,0);
}
};