现在的位置: 首页 > 综合 > 正文

Leetcode: Sum Root to Leaf Numbers

2014年02月21日 ⁄ 综合 ⁄ 共 1503字 ⁄ 字号 评论关闭

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.

第一反应是一个相当复杂的东西,权当练习STL了吧。

/**
 * Definition for binary tree
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
#include <unordered_map>
#include <queue>

class Solution {
public:
    int sumNumbers(TreeNode *root) {
        if (root == NULL) {
            return 0;
        }
        
        int sum = 0;
        TreeNode *cur = NULL;
        unordered_map<TreeNode*, int> node_values;
        node_values[root] = root->val;
        queue<TreeNode*> nodes;
        nodes.push(root);
        
        while (!nodes.empty()) {
            cur = nodes.front();
            nodes.pop();
            auto node_value = node_values.find(cur);
            assert(node_value != node_values.end());
            if (cur->left == NULL && cur->right == NULL) {
                sum += node_value->second;
            }
            else {
                if (cur->left != NULL) {
                    node_values[cur->left] = node_value->second * 10 + cur->left->val;
                    nodes.push(cur->left);
                }
                if (cur->right != NULL) {
                    node_values[cur->right] = node_value->second * 10 + cur->right->val;
                    nodes.push(cur->right);
                }
            }
        }
        
        return sum;
    }
};

其实可以用递归:

class Solution {
public:
    int sumNumbers(TreeNode *root) {
        if (root == NULL) {
            return 0;
        }
        
        return sumUtil(root, 0);
    }
    
    int sumUtil(TreeNode *cur, int sum) {
        int result = 0;
        sum = sum * 10 + cur->val;
        if (cur->left == NULL && cur->right == NULL) {
            result = sum;
        }
        else {
            if (cur->left != NULL) {
                result += sumUtil(cur->left, sum);
            }
            if (cur->right != NULL) {
                result += sumUtil(cur->right, sum);
            }
        }
        
        return result;
    }
};

抱歉!评论已关闭.