码迷,mamicode.com
首页 > 其他好文 > 详细

leetcode@ [129] Sum Root to Leaf Numbers (DFS)

时间:2016-01-11 22:16:10      阅读:136      评论:0      收藏:0      [点我收藏+]

标签:

https://leetcode.com/problems/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.

技术分享
/**
 * 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:
    void travel(vector<vector<int> >& nums, vector<int>& load, TreeNode* root) {
        if(!(root->left) && !(root->right)) {
            nums.push_back(load);
            return;
        }
        
        if(root->left) {
            load.push_back(root->left->val);
            travel(nums, load, root->left);
            load.pop_back();
        }
        if(root->right) {
            load.push_back(root->right->val);
            travel(nums, load, root->right);
            load.pop_back();
        }
    }
    int sumNumbers(TreeNode* root) {
        if(root == NULL)  return 0;
        
        vector<vector<int> > nums;
        vector<int> load;
        int res = 0;
        
        load.push_back(root->val);
        travel(nums, load, root);
        
        for(int i=0; i<nums.size(); ++i) {
            int rhs = 0;
            for(int j=0; j<nums[i].size(); ++j) {
                rhs = rhs * 10 + nums[i][j];
            }
            res += rhs;
        }
        return res;
    }
};
View Code

 

leetcode@ [129] Sum Root to Leaf Numbers (DFS)

标签:

原文地址:http://www.cnblogs.com/fu11211129/p/5122607.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!