[leetcode] 129. Sum Root to Leaf Numbers 解题报告

题目链接: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 DFS(TreeNode* root, int& sum, int cur)
    {
        if(!root) return;
        cur = cur*10 + root->val;
        if(!root->left && !root->right) sum += cur;
        DFS(root->left, sum, cur);
        DFS(root->right, sum, cur);
    }
    
    int sumNumbers(TreeNode* root) {
        if(!root) return 0;
        int ans = 0;
        DFS(root, ans, 0);
        return ans;
    }
};


你可能感兴趣的:(leetcode,binary,tree,DFS)