您的位置:首页 > 其它

Sum-root-to-leaf-Numbers

2018-03-23 14:54 260 查看

题目描述

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:
    int sumNumbers(TreeNode *root) {       if(root==NULL) return 0;         return sumRec(root, 0);       }    int sumRec(TreeNode *root, int presum)     {          int x = presum*10 + root->val;        if(root->left==NULL && root->right==NULL)  //左右子树都没有;        {              return x;          }         if(root->left==NULL)          //没有左子树;        {              return sumRec(root->right, x);          }        if(root->right==NULL)       //没有右子树        {              return sumRec(root->left, x);          }        return sumRec(root->left, x) + sumRec(root->right, x);     //都要左右子树;      }  };
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: