[C++]LeetCode: 94 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.

思路:

观察题目给的返回值是int,可知测试集的树高度不超过10,这道题我们可以不考虑溢出的情况,如果没有题目限定,需要考虑。用递归来实现,本质上就是先序遍历。考虑递归条件和结束条件。我们的目标是把从根到叶子结点的所有路径得到的整数累加起来。递归条件就是把当前sum值乘以10再加上当前节点的值,传给下一个函数(123 = 12 *10 + 3),随着递归的深度,我们最顶端的数值会不断乘以10,这样就不需要计算这条路径的深度再看10的幂是多少了。进行递归,我们把左右子树的总和相加。结束条件是,如果一个节点的叶子,我们将目前的累加结果乘以10再加叶子节点值,返回后加到最终综合种。如果节点时空节点,而不是叶子结点,不需要加到结果中,返回0.

复杂度:先序遍历则,时间复杂度O(N),空间是栈大小,O(log(n))

树的题目在LeetCode中还是有比较大的比例的,不过除了基本的递归和非递归的遍历之外,其他大部分题目都是用递归方式来求解特定量.递归法是解决树的问题最常用的办法。

AC 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:
    int sumNumbers(TreeNode *root) {
        return sumNumbers_helper(root, 0);
    }

private:
    int sumNumbers_helper(TreeNode* root, int x)
    {
        if(root == NULL) return 0;
        if(root->left == NULL && root->right == NULL)
        {
            return 10 * x + root->val;
        }
        
        return sumNumbers_helper(root->left, 10*x + root->val) + sumNumbers_helper(root->right, 10*x + root->val);
    }
};



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值