Given a Binary Tree Containing digits from0-9
Only, each root-to-leaf path cocould represent a number.
An example is the root-to-leaf path1->2->3
Which represents the number123
.
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 = 12 + 13 =25
.
Basic Ideas:
Pre-order traversal.
Use a global variable to record and.
Each time a leaf node receives a number, it accumulates and coexist with global variables.
The actual running time on leetcode is 4 ms.
/** * 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 sum = 0; sumNumbers(root, 0, sum); return sum; } void sumNumbers(TreeNode* root, int number, int &sum) { if (!root) return; number = number * 10 + root->val; if (!root->left && !root->right) sum += number; sumNumbers(root->left, number, sum); sumNumbers(root->right, number, sum); }};
Ultimate Edition:
You can use the function return value to replace the above global variables and (the third variable of the function ).
If it is a page subnode, an integer is returned.
If it is an intermediate node, return the integer and between its left and right subnumbers.
class Solution {public: int sumNumbers(TreeNode* root) { return sumNumbers(root, 0); } int sumNumbers(TreeNode *root, int number) { if (!root) return 0; number = number * 10 + root->val; if (!root->left && !root->right) return number; return sumNumbers(root->left, number) + sumNumbers(root->right, number); }};
Sum root to leaf numbers -- leetcode