Sum Root to Leaf Numbers

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.

分析:DFS。代码如下:

class Solution {
public:
    int sumNumbers(TreeNode *root) {
        int result = 0;
        if(root == NULL) return result;
        dfs(root, result, 0);
        return result;
    }
    
    void dfs(TreeNode *root, int &result, int cur_sum){
        cur_sum = cur_sum*10 + root->val;
        if(root->left == NULL && root->right == NULL){
            result += cur_sum;
        }else{
            if(root->left)
                dfs(root->left, result, cur_sum);
            if(root->right)
                dfs(root->right, result, cur_sum);
        }
    }
};

 

posted on 2014-08-07 17:25  Ryan-Xing  阅读(86)  评论(0)    收藏  举报