[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 value, int& sum)
    {
        value = value*10 + root->val;
        if(!root->left && !root->right)//如果是叶子结点,则存到结果中去
        {
            sum += value;
            return;
        }
        if(root->left) DFS(root->left, value, sum);
        if(root->right) DFS(root->right, value, sum);
    }
    int sumNumbers(TreeNode* root) {
        if(!root)   return 0;
        int sum = 0;
        DFS(root, 0, sum);
        return sum;
    }
};


你可能感兴趣的:(LeetCode,算法,二叉树,tree,binary,DFS)