[Leetcode] 129. 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.

思路

递归在通常情况下是先解决子问题,然后再汇总子问题,得到母问题的解。然而该题目略有不同:我们需要先解决母问题,然后再去递归地解决子问题。而递归的边界就是我们遇到了叶子节点。所以每次当我们遇到一个叶子结点的时候,就更新全局结果,否则就递归地解决子问题。代码挺容易理解的。

代码

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode(int x) : val(x), left(NULL), right(NULL) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        if (root == NULL) {
            return 0;
        }
        int ret = 0;
        sumNumbers(root, ret, 0);
        return ret;
    }
private:
    void sumNumbers(TreeNode* root, int &ret, int parent_sum) { // precondition: root cannot be NULL
        int value = parent_sum * 10 + root->val;
        if (!root->left && !root->right) {
            ret += value;
            return;
        }
        if (root->left) {
            sumNumbers(root->left, ret, value);
        }
        if (root->right) {
            sumNumbers(root->right, ret, value);
        }
    }
};

你可能感兴趣的:(IT公司面试习题)