Wednesday, April 23, 2014

[LeetCode] Sum Root to Leaf Numbers

Problem Statement (link):
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.
Analysis:
This problem should be straightforward, we need to traverse to each leaf to form a number, and add all the numbers together. We use a vector<int> to store the traversed node's value.

Code:
/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */

class Solution {
public:
    // Recursive - preorder
    int sumNumbers(TreeNode *root) {
        if (root==NULL) return 0;
        vector<int> sum;
        int nodeSum=0;
        dfs(root, sum, nodeSum);
        nodeSum=0;

        for (int i=0; i<sum.size(); i++) {
            nodeSum += sum[i];
        }

        return nodeSum;
    }

    void dfs(TreeNode *node, vector<int> & sum, int nodeSum)  {
        nodeSum = 10*nodeSum+node->val;
        if (node->left==NULL && node->right==NULL) {
            sum.push_back(nodeSum);
        }
        else {
            if (node->left!=NULL)
                dfs(node->left, sum, nodeSum);
            if (node->right!=NULL)
                dfs(node->right, sum, nodeSum);
        }
    }
};

No comments:

Post a Comment