[LeetCode-129] Sum Root to Leaf Numbers

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.

 

历遍而已呀,累加一下val就好~

 

 1 /**
 2  * Definition for binary tree
 3  * struct TreeNode {
 4  *     int val;
 5  *     TreeNode *left;
 6  *     TreeNode *right;
 7  *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 8  * };
 9  */
10 class Solution {
11 public:
12     int sumNumbers(TreeNode *root) {
13         // Start typing your C/C++ solution below
14         // DO NOT write int main() function
15         if (NULL == root) {
16             return 0;
17         }
18         stack<TreeNode*> node_stack;
19         TreeNode *pf = NULL, *psl = NULL, *psr = NULL;
20         node_stack.push(root);
21         int sum = 0;
22         while (!node_stack.empty()) {
23             TreeNode* pf = node_stack.top();
24             node_stack.pop();
25             if ((NULL == pf->left) && (NULL == pf->right)) {
26                 sum += pf->val;
27             } else {
28                 if (NULL != (psl = pf->left)) {
29                     psl->val += pf->val * 10;
30                     node_stack.push(psl);
31                 }
32                 if (NULL != (psr = pf->right)) {
33                     psr->val += pf->val * 10;
34                     node_stack.push(psr);
35                 }
36             }
37         }
38         return sum;
39     }
40 };
View Code

 

posted on 2013-08-19 19:15  似溦若岚  阅读(156)  评论(0编辑  收藏  举报

导航