sum-root-to-leaf-numbers

来源:互联网 发布:蜂窝移动数据快捷方式 编辑:程序博客网 时间:2024/06/08 10:59

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;        int sum = 0;        return sumhelper(root,sum);    }    int sumhelper(TreeNode *root,int sum){        if(root==NULL)            return 0;        sum = sum * 10 + root->val;        if(root->left==NULL && root->right==NULL){            return sum;        }        return sumhelper(root->left,sum) + sumhelper(root->right,sum);    }};
原创粉丝点击