leetcode #129 in cpp

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.


Solution:

from the root to a leaf node, make the number represented by the path. Then we store all numbers and add them up.  

Code:

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        vector<int> res; 
        getSum(root, 0, res);
        int sum = 0;
        for(int i = 0; i < res.size(); i ++){
            sum+=res[i];
        }
        return sum; 
    }
    void getSum(TreeNode*node,int num,  vector<int> &res){
        if(!node) return;
        if(!node->left && !node->right) {//if reach leaf node,store the sum
            res.push_back(num*10 + node->val);
            return;
        }
        num=num*10 + node->val; 
        getSum(node->left, num, res);//pass to left
        getSum(node->right, num, res);//pass to right;
    }
};


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章