您的位置:首页 > 其它

sum-root-to-leaf-numbers

2016-06-29 10:35 316 查看
Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.

An example is the root-to-leaf path1->2->3which represents the number123.

Find the total sum of all root-to-leaf numbers.

For example,

1
/ \
2   3


The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.

Return the sum = 12 + 13 =25.

我的代码

**
* Definition for binary tree
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void sum(TreeNode *root,vector<int>&path,int &res)
{
  if(root==NULL)
      return;
  path.push_back(root->val);
  if(root->left==NULL && root->right==NULL)
  {
  int sum=0;
  for(int i=0;i<path.size();i++)
  {
    sum=sum*10+path[i];
  }

  res+=sum;
  path.pop_back();
  }else
  {
    sum(root->left,path,res);
    sum(root->right,path,res);
    path.pop_back();
  }
}
int sumNumbers(TreeNode *root) {
  vector<int>path;
  int res=0;
  sum(root,path,res);
  return res;
}
};

别人的代码

int getsum(TreeNode *root,int num)
{
  if(root==NULL)
      return 0;
  num=num*10+root->val;
  if(root->left==NULL &&root->right==NULL)
      return num;
  return getsum(root->left,num)+getsum(root->right,num);
}
int sumNumbers(TreeNode *root) {

  int sum=0;
  sum=getsum(root,0);
  return sum;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: