Friday, June 24, 2016

129. Sum Root to Leaf Numbers

When I first saw this problem, I was thinking of constructing a DFS algorithm that every time I need to compute the depth of the left child and its sum as well as the depth of the right child and its sum. For current node, the sum will be the 10^left_depth + left_sum + 10^right_depth + right_sum. This is a bottom-to-top way and turns out not working well. Then I think of the top-to-bottom way. The function will take the sum from the parent and compute the sum at current node, pass the sum to its left and right children and sum up the sum of left and right children.

1:  class Solution {  
2:  public:  
3:    int sumNumbers(TreeNode* root) {  
4:      return helper(root, 0);  
5:    }  
6:    int helper(TreeNode* root, int val) {  
7:      if (root == NULL) return 0;  
8:      val = 10*val + root->val;  
9:      if (root->left == NULL && root->right == NULL) {  
10:        return val;  
11:      }  
12:      return helper(root->left, val)+helper(root->right, val);  
13:    }  
14:  };  

No comments:

Post a Comment