`

Sum Root to Leaf Numbers

 
阅读更多
/**
 * 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) {
        vector<vector<int>> ap;
        vector<int> pv;
        allPath(root, pv, ap);
        int c = ap.size();
        int sum = 0;
        for(int i = 0; i < c; i++) {
            sum += getNum(ap[i]);
        }
        return sum;
    }
    
    void allPath(TreeNode *root, vector<int> &pv, vector<vector<int>> &ap) {
        if(!root) return;
        
        pv.push_back(root->val);
        if(!root->left && !root->right) {
            ap.push_back(pv);
            pv.pop_back();
            return;
        }
        
        allPath(root->left, pv, ap);
        allPath(root->right, pv, ap);
        pv.pop_back();
    }
    
    int getNum(vector<int> vec) {
        int n = vec.size();
        int sum = 0;
        for(int i = 0; i < n; i++) {
            sum = sum*10 + vec[i];
        }
        return sum;
    }
};

 

欢迎关注微信公众号——计算机视觉:

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics