题目考察的知识点:二叉树的遍历

题目解答方法的文字分析:遍历这棵树,然后寻找叶子结点,保存经过加工的值,最后求和

本题解析所用的编程语言:c++

/**
 * struct TreeNode {
 *	int val;
 *	struct TreeNode *left;
 *	struct TreeNode *right;
 *	TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 * };
 */
class Solution {
public:
    /**
     * 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
     *
     * 
     * @param root TreeNode类 
     * @return int整型
     */
    void combine(TreeNode* root, vector<int>& v, int x)
    {
        if (root == nullptr)
            return;
        x = x*10 + root->val;
        if (root->left == nullptr && root->right == nullptr)
            v.push_back(x);
        combine(root->left, v, x);
        combine(root->right, v, x);
    }
    int sumNumbers(TreeNode* root) {
        // write code here
        vector<int> v;
        combine(root, v, 0);
        int sum = 0;
        for (auto& x : v)
            sum += x;
        return sum;
    }
};