[LeetCode] Sum Root to Leaf Numbers

来源:互联网 发布:淘宝客服组长工作计划 编辑:程序博客网 时间:2024/05/20 01:35

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:    int sumNumbers(TreeNode* root) {        int result = 0;        helper(root, 0, result);        return result;    }        void helper(TreeNode* root, int temp, int& result){        if(root==NULL){            return;        }        temp = temp*10;        temp = temp + root->val;        if(root->left==NULL && root->right==NULL){            result += temp;        }        helper(root->left, temp, result);        helper(root->right, temp, result);    }};


0 0