Given a binary tree containing digits from only 0-9
, 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 Path1->2
Represents the number12
.
The Root-to-leaf Path1->3
Represents the number13
.
Return the sum = + = 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 Sumnumber (treenode* root, int sum,int& result) { if (root = NULL) return; Direct return sum = sum * + root->val; if (Root->left = = NULL && Root->right = = null) {//Add sum returns result + = sum; return; } Sumnumber (Root->left, sum,result); Sumnumber (Root->right, Sum,result); } int sumnumbers (treenode* root) { int result = 0;sumnumber (root, 0, result); return result;} ;
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Leetcode ($): Sum Root to Leaf Numbers