129. 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
.
1 class Solution { 2 public: 3 int sum; 4 void backtrack(TreeNode* root, int path) { 5 if(root == nullptr) return; 6 if(root->left == nullptr && root->right == nullptr) { 7 path = path * 10 + root->val; 8 sum += path; 9 return; 10 } 11 path = path * 10 + root->val; 12 backtrack(root->left,path); 13 backtrack(root->right,path); 14 path = path/10; 15 } 16 int sumNumbers(TreeNode* root) { 17 backtrack(root,0); 18 return sum; 19 } 20 };