|
| 1 | +/* |
| 2 | + |
| 3 | + Date: Jan 02, 2014 |
| 4 | + Problem: Sum Root to Leaf Numbers |
| 5 | + Difficulty: Easy |
| 6 | + Source: https://oj.leetcode.com/problems/sum-root-to-leaf-numbers/ |
| 7 | + Notes: |
| 8 | + Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number. |
| 9 | + An example is the root-to-leaf path 1->2->3 which represents the number 123. |
| 10 | + Find the total sum of all root-to-leaf numbers. |
| 11 | + For example, |
| 12 | + 1 |
| 13 | + / \ |
| 14 | + 2 3 |
| 15 | + The root-to-leaf path 1->2 represents the number 12. |
| 16 | + The root-to-leaf path 1->3 represents the number 13. |
| 17 | + Return the sum = 12 + 13 = 25. |
| 18 | +
|
| 19 | + Solution: 1. Recursion (add to sum when reaching the leaf). |
| 20 | + 2. Iterative solution. |
| 21 | + */ |
| 22 | + |
| 23 | +/** |
| 24 | + * Definition for binary tree |
| 25 | + * struct TreeNode { |
| 26 | + * int val; |
| 27 | + * TreeNode *left; |
| 28 | + * TreeNode *right; |
| 29 | + * TreeNode(int x) : val(x), left(NULL), right(NULL) {} |
| 30 | + * }; |
| 31 | + */ |
| 32 | +class Solution { |
| 33 | +public: |
| 34 | + int sumNumbers(TreeNode *root) { |
| 35 | + return sumNumbers_1(root); |
| 36 | + } |
| 37 | + |
| 38 | + int sumNumbers_1(TreeNode *root) { |
| 39 | + int sum = 0; |
| 40 | + sumNumbersRe(root, 0, sum); |
| 41 | + return sum; |
| 42 | + } |
| 43 | + |
| 44 | + void sumNumbersRe(TreeNode *node, int num, int &sum) { |
| 45 | + if (!node) return; |
| 46 | + num = num * 10 + node->val; |
| 47 | + if (!node->left && !node->right) { |
| 48 | + sum += num; |
| 49 | + return; |
| 50 | + } |
| 51 | + sumNumbersRe(node->left, num, sum); |
| 52 | + sumNumbersRe(node->right, num, sum); |
| 53 | + } |
| 54 | + |
| 55 | + int sumNumbers_2(TreeNode *root) { |
| 56 | + if (!root) return 0; |
| 57 | + int res = 0; |
| 58 | + queue<pair<TreeNode *, int>> q; |
| 59 | + q.push(make_pair(root, 0)); |
| 60 | + while(!q.empty()) |
| 61 | + { |
| 62 | + TreeNode *node = q.front().first; |
| 63 | + int sum = q.front().second * 10 + node->val; |
| 64 | + q.pop(); |
| 65 | + if (!node->left && !node->right) |
| 66 | + { |
| 67 | + res += sum; |
| 68 | + continue; |
| 69 | + } |
| 70 | + if (node->left) |
| 71 | + q.push(make_pair(node->left, sum)); |
| 72 | + if (node->right) |
| 73 | + q.push(make_pair(node->right, sum)); |
| 74 | + } |
| 75 | + return res; |
| 76 | + } |
| 77 | +}; |
0 commit comments