菱纱梦

导航

Sum Root to Leaf Numbers <leetcode>

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 /**
 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  struct node
11  {
12      TreeNode *root;
13      int val;
14  };
15 class Solution {
16 public:
17     int result;
18     bool k=true;
19     int sumNumbers(TreeNode *root) {
20         if(NULL==root)  return 0;
21         result=0;
22         vector<node>  temp;
23         temp.clear();
24         doit(root,temp);
25         return result;
26     }
27     
28     void doit(TreeNode* &root,vector<node>  temp)
29     {
30         if(NULL==root->left&&NULL==root->right)
31         {
32             if(k)  result+=root->val;
33             
34             else result+=temp.back().val*10+root->val;
35             return;
36         }
37         else
38         {
39             node n;
40             if(k) 
41             {
42                 n.val=root->val;
43                 k=false;
44             }
45             else   n.val=temp.back().val*10+root->val;
46             n.root=root;
47             temp.push_back(n);
48             if(NULL!=root->left)
49             {
50               doit(root->left,temp);
51             }
52             if(NULL!=root->right)
53             {
54                 doit(root->right,temp);
55             }
56         }
57     }
58 };

 

posted on 2014-09-09 20:25  菱纱梦  阅读(163)  评论(0编辑  收藏  举报