Friday, May 30, 2014

LeetCode: Sum Root to Leaf Numbers

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.


We can start from the root node and perform a breadth first search. If one path reaches to the end, push the current num into a list and finally add them together.

C++ Code:

/*
 * func: root_leaf_sum_helper
 * goal: helper function for root_leaf_sum to perform BFS
 * @param root: root node of the tree
 * @param vec: vector to store each value
 * @param num: current num in string format
 * return:
 */
void root_leaf_sum_helper(TreeNode *root, vector<string> &vec, string num){
    if(root == nullptr){
        return;
    }else if(root->left == nullptr && root->right == nullptr){
        num += char(root->val + '0');
        vec.emplace_back(num);
        return;
    }else{
        num += char(root->val + '0');
        root_leaf_sum_helper(root->right, vec, num);
        root_leaf_sum_helper(root->left, vec, num);
    }
}

/*
 * func: root_leaf_sum
 * goal: find the total sum of all root-to-leaf numbers
 * @param root: root node of the tree
 * return: total sum
 */
int root_leaf_sum(TreeNode *root){
    vector<string> vec;
    string num = "";
    root_leaf_sum_helper(root, vec, num);
    int result = 0;
    for(const string &str : vec){
        result += atoi(str.c_str());
    }
    return result;
}

Python Code:

# func: find the sum of all numbers constructed from root to leaf
# @param root: root node of the tree
# @return: sum
def sum_root_leaf(root):
    if not root:
        return 0
    else:
        def sum_root_leaf_helper(val, node):
            if not node.left and not node.right:
                return val
            elif not node.left:
                return sum_root_leaf_helper(val * 10 + node.right.val, node.right)
            elif not node.right:
                return sum_root_leaf_helper(val * 10 + node.left.val, node.left)
            else:
                return sum_root_leaf_helper(val * 10 + node.left.val, node.left) + \
                sum_root_leaf_helper(val * 10 + node.right.val, node.right)
        return sum_root_leaf_helper(root.val, root)

No comments:

Post a Comment