Sum Root to Leaf Numbers

http://oj.leetcode.com/problems/sum-root-to-leaf-numbers/
Another problem from Leetcode that I came up with two different solutions.
The first solution idea is to get paths from root to leaves first, compute the sum later. Those paths can be easily discovered by depth first search, while each path can be transformed to integer easily.
The second solution is much more elegant. There is no need to keep track of any paths, we calculate the sum as we go deeper from root to leaves. It runs a lot faster than the previous solution (12ms vs 36ms).

Second solution

class Solution {
public:
    int sumNumbers(TreeNode *root) {
       return sumNumbers(root,0);
    }
    int sumNumbers(TreeNode* root, int curr){
        if(!root)
            return 0;
        curr=curr*10+root->val;
        if(!root->left && !root->right)
            return curr;
        return sumNumbers(root->left,curr)+sumNumbers(root->right,curr);
    }
};

First solution

class Solution {
public:
    vector<int> pow10;
    int sumNumbers(TreeNode *root) {
        if(!root)
            return 0;
        pow10.resize(10);
        pow10[0]=1;
        for(int i=1; i<pow10.size();i++){
            pow10[i]=10*pow10[i-1];
        }
        list<int> path{root->val};
        return sumNumbers(root,path);
    }
    
    int sumNumbers(TreeNode *root, list<int> &path){
        if(!root->left && !root->right){
            return calculateSum(path);
        }
        int sum = 0;
        if(root->left){
            path.push_back(root->left->val);
            sum+=sumNumbers(root->left, path);
            path.pop_back();
        }
        if(root->right){
            path.push_back(root->right->val);
            sum+=sumNumbers(root->right, path);
            path.pop_back();
        }
        return sum;
    }
    
    int calculateSum(list<int>& path){
        int sum = 0;
        int n = path.size();
        int i =0;
        for(int p:path){
            sum+=p*pow10[n-1-i];
            i++;
        }
        return sum;
    }
};
Advertisements
This entry was posted in Computer Science, LeetCode and tagged , , , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s