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.

针对每一个结点, 都把它当作叶子来处理, 这样, 每个结点都会有个值, 其值的大小是父结点的值*10, 返回值就加上自己的结点

/**
 * 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 vers(TreeNode *root, int path)
    {
        if(NULL==root)return 0;
        if(NULL==root->left&&NULL==root->right)
            return path * 10 + root->val;
        return vers(root->left, path * 10 + root->val) + vers(root->right, path * 10 + root->val);
    }
    int sumNumbers(TreeNode *root)
    {
        int path = 0;
        return vers(root, path);
    }
};


posted @ 2014-03-08 16:33  海滨银枪小霸王  阅读(112)  评论(0)    收藏  举报