Sum Root to Leaf Numbers

题目大意:求根到叶子节点的所有路径得到的所有整数和


解题思路:递归


/**
 * 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) {
        return sumNumbers(root, 0);
    }
private:
    int sumNumbers(TreeNode* root, int part) {
        if(root == NULL) {
            return 0;
        }
        part = part * 10 + root->val;
        if(!root->left && !root->right) {
            return part;
        }
        return sumNumbers(root->left, part) + sumNumbers(root->right, part);
    }
};



你可能感兴趣的:(leetcode)