2013年8月15日星期四

Sum Root to Leaf Numbers

[leetcode不能查看ac代码,开贴暂存]
description:
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.
solve:
/**
 * 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) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        int res = 0;
        run(root, 0, res);
        return res;
     
    }
    void run(TreeNode* root, int out, int& res) {
        if(root == NULL) {
            return;
        }
        out = out * 10 + root->val;
     
        if(root->right == NULL && root->left == NULL) {
            res += out;
        } else {
            run(root->right, out, res);
            run(root->left, out, res);
        }
    }   return v;
};

没有评论:

发表评论