# Sum root to leafs Nums

Source: Internet
Author: User

Given a Binary Tree Containing digits from`0-9`Only,
Each root-to-leaf path cocould 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 binary tree * struct TreeNode { *     int val; *     TreeNode *left; *     TreeNode *right; *     TreeNode(int x) : val(x), left(NULL), right(NULL) {} * }; */class Solution {public:    int sum;vector<int> tempNum;int toInt(vector<int>& num){        if(num.size() == 0)            return 0;int ret = 0;for(int i = 0; i < num.size(); i ++)ret = ret * 10 + num[i];return ret;}void dfs(TreeNode* root){if(root == NULL){            return;}        tempNum.push_back(root->val);        if(root->left == NULL && root->right == NULL)        {            sum += toInt(tempNum);        }dfs(root->left);dfs(root->right);tempNum.pop_back();}int sumNumbers(TreeNode *root) {// Start typing your C/C++ solution below// DO NOT write int main() functionsum = 0;        tempNum.clear();dfs(root);return sum;}};`

Only leaf nodes can be added. Determine whether the node is a leaf node.

Related Keywords:

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

## A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

• #### Sales Support

1 on 1 presale consultation

• #### After-Sales Support

24/7 Technical Support 6 Free Tickets per Quarter Faster Response

• Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.