runnig

[leetcode] 129 Sum Root to Leaf Numbers (done)

Feb 26th, 2013
157
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.04 KB | None | 0 0
  1. /*
  2. http://leetcode.com/onlinejudge#question_129
  3.  
  4. Sum Root to Leaf Numbers
  5. Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
  6.  
  7. An example is the root-to-leaf path 1->2->3 which represents the number 123.
  8.  
  9. Find the total sum of all root-to-leaf numbers.
  10.  
  11. For example,
  12.  
  13.     1
  14.    / \
  15.   2   3
  16. The root-to-leaf path 1->2 represents the number 12.
  17. The root-to-leaf path 1->3 represents the number 13.
  18.  
  19. Return the sum = 12 + 13 = 25.
  20. */
  21. class Solution {
  22. public:
  23.     int sumNumbers(TreeNode *root, int v = 0) {
  24.        
  25.         if(NULL == root) { return v; }
  26.        
  27.         int x = v * 10 + root->val;
  28.        
  29.         if(!root->left && !root->right)
  30.         {
  31.             return x;
  32.         }
  33.        
  34.         int L = 0, R = 0;
  35.        
  36.         if(root->left)
  37.         {
  38.             L = sumNumbers(root->left, x);                  
  39.         }
  40.         if(root->right)
  41.         {
  42.             R = sumNumbers(root->right, x);        
  43.         }
  44.         return L + R;
  45.        
  46.     }
  47. };
Advertisement
Add Comment
Please, Sign In to add comment