129. Sum Root to Leaf Numbers

来源:互联网 发布:graph cut算法原理 编辑:程序博客网 时间:2024/06/05 14:58

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 getSum(TreeNode *root, int cur_sum){        // 终止条件        if (root == NULL) return 0;        // 处理叶子节点        if (root->left == NULL && root->right == NULL)            return cur_sum * 10 + root->val;        // 递归过程        return getSum(root->left, cur_sum * 10 + root->val) + getSum(root->right, cur_sum * 10 + root->val);    }    // 129. Sum Root to Leaf Numbers     int sumNumbers(TreeNode* root) {        // 得到root为根的和        return getSum(root, 0);    }}

二叉树具有天然的递归结构,这类问题要想清楚:

  1. 递归终止条件(包括根节点为NULL怎么处理,遇到叶子节点怎么处理);
  2. 递归的过程(如何定义一个递归求解过程,把一个大规模的问题缩小到相同套路的子问题,从而缩小规模);
  3. 一旦递归过程想清楚了,就可以假设子问题已经得到解决,进而在此基础上求解更大规模的问题。