2014.1.1 19:55
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
.
Solution:
The solution is plain, traverse the tree and add up the numbers at leaf nodes.
1->2->3 forms "123", that's (1 * 10 + 2) * 10 + 3. Then you know how the recursion is done.
Time and space complexities are both O(n), where n is the number of nodes in the tree. The space complexity comes from the local paramater in recursive calls.
Accepted code:
1 //1CE, 2WA, 1AC 2 /** 3 * Definition for binary tree 4 * struct TreeNode { 5 * int val; 6 * TreeNode *left; 7 * TreeNode *right; 8 * TreeNode(int x) : val(x), left(NULL), right(NULL) {} 9 * }; 10 */ 11 class Solution { 12 public: 13 int sumNumbers(TreeNode *root) { 14 // IMPORTANT: Please reset any member data you declared, as 15 // the same Solution instance will be reused for each test case. 16 17 if(root == nullptr){ 18 return 0; 19 } 20 21 result = 0; 22 traverse(root, root->val); 23 24 return result; 25 } 26 private: 27 int result; 28 void traverse(TreeNode *root, int weight) { 29 // Which level should 'weight' represent, vague... 30 // That's why you got two WAs here!!! 31 if(root == nullptr){ 32 return; 33 } 34 35 if(root->left == nullptr && root->right == nullptr){ 36 result += weight; 37 return; 38 } 39 40 if(root->left != nullptr){ 41 traverse(root->left, weight * 10 + root->left->val); 42 } 43 if(root->right != nullptr){ 44 traverse(root->right, weight * 10 + root->right->val); 45 } 46 } 47 };