leetcode --sum-root-to-leaf-numbers

Given a binary tree containing digits from0-9only, each root-to-leaf path could represent a number.
An example is the root-to-leaf path1->2->3which represents the number123.
Find the total sum of all root-to-leaf numbers.
For example,
1
/ |
2 3
The root-to-leaf path1->2represents the number12.
The root-to-leaf path1->3represents the number13.
Return the sum = 12 + 13 =25.


思路:本题可以按照先序遍历来求和,对于每个结点,采用 temp = value* 10 + node->val来更新值。注意先序遍历的写法,不要多考虑情况,一开始我加的判断太多了,其实根本不需要,只需要判断传入的Node是否为空即可!!而不需要预先做判断。

代码如下:

/**
 * 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) {
        if(root == nullptr) return 0;
        return sum(root,0);
    }
    int sum(TreeNode *root ,int value) {
        if(root == nullptr) 
            return 0;
        int temp = value * 10 + root->val;
        if(root->left == nullptr && root->right == nullptr) return temp;
        return sum(root->right,temp) + sum(root->left,temp);
    }
};

你可能感兴趣的:(leetcode --sum-root-to-leaf-numbers)