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.

Note: A leaf is a node with no children.

Example:

Input: [1,2,3]
    1
   / \
  2   3
Output: 25
Explanation:
The root-to-leaf path 1->2 represents the number 12.
The root-to-leaf path 1->3 represents the number 13.
Therefore, sum = 12 + 13 = 25.
Example 2:

Input: [4,9,0,5,1]
    4
   / \
  9   0
 / \
5   1
Output: 1026
Explanation:
The root-to-leaf path 4->9->5 represents the number 495.
The root-to-leaf path 4->9->1 represents the number 491.
The root-to-leaf path 4->0 represents the number 40.
Therefore, sum = 495 + 491 + 40 = 1026.

题意分析: 

给定一个仅包含数字0-9的二叉树,每个从根节点到叶子节点的路径代表一个数,请求得所有路径代表的数之和。

方法一(递归法)

与“https://blog.csdn.net/Vensmallzeng/article/details/95324164”中的方法一基本一样,但该方法的时间复杂度、空间复杂度都是不尽人意的。

解题代码如下:

class Solution{
public:
    int sumNumbers(TreeNode* root){
        vector<vector<int>> temp;
        int res = 0;
        temp = sumNumbers_son(root);

        for (int i = 0; i < temp.size(); i++) {
            int total = 0;
            for (int j = 0; j < temp[i].size(); j++) {
                total += temp[i][j]*pow(10,j);
            }
            res += total;
        }
        return res;
    }


    vector<vector<int>> sumNumbers_son(TreeNode* root){
        vector<vector<int>> res;
        if(root == NULL) return res;
        if(root->left == NULL && root->right == NULL) {res.push_back({root->val}); return res;}

        vector<vector<int>> leftpath = sumNumbers_son(root->left);
        for (int i = 0; i < leftpath.size(); i++) {leftpath[i].push_back(root->val); res.push_back(leftpath[i]);}
        vector<vector<int>> rightpath = sumNumbers_son(root->right);
        for (int i = 0; i < rightpath.size(); i++) {rightpath[i].push_back(root->val); res.push_back(rightpath[i]);}
        return res;
    }
};

提交后的结果如下:

 

方法二(递归法)

本题并不是简单的把各个节点值相加,而是每当遇到一个新子结点时,要把其父结点的值扩大10倍之后再与其值相加。若遍历到叶子结点,则将当前的累加结果sum返回,否则需对其左右子结点分别进行递归调用,最后将两部分结果相加即为所求之和。

解题代码如下:

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

提交后的结果如下:

 

 

 

日积月累,与君共进,增增小结,未完待续。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值