4/06/2014

Leetcode -- Sum Root to Leaf Numbers

/**  
  * Definition for binary tree  
  * struct TreeNode {  
  *   int val;  
  *   TreeNode *left;  
  *   TreeNode *right;  
  *   TreeNode(int x) : val(x), left(NULL), right(NULL) {}  
  * };  
  */  
 class Solution {  
 public:  
   int sumNumbers(TreeNode *root) {  
     int sum = 0;  
     divePath(root, 0, sum);  
     return sum;  
   }  
   void divePath(TreeNode* root, int num, int& sum) {  
     if(root == NULL) {  
       return;  
     }  
     if(root->left == NULL && root->right == NULL) {  
       sum += num * 10 + root->val;  
       return;  
     }  
     if(root->left != NULL) {  
       divePath(root->left, num * 10 + root->val, sum);  
     }  
     if(root->right != NULL) {  
       divePath(root->right, num * 10 + root->val, sum);  
     }  
   }  
 };

No comments: