Leetcode 129 Sum Root to leaf Numbers

Input: root = [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.

题目理解不难, 方法一也很固定。递归遍历整个树的node。

并且动态更新number数值。 val*10+root->val

当到达叶子节点时候把最新的val*10+root->val 加到结果的ret里面。

然后就这样遍历所有的叶子节点。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int ret=0;
    void help(TreeNode* root, int val) {
        if(root->left == nullptr && root->right == nullptr) {
            val = val*10 + root->val;
            ret += val;
            return;
        }
        
        if(root->left) {
            help(root->left, val*10 + root->val);
        }
        
        if(root->right) {
            help(root->right, val*10 + root->val);
        }
        
        return;
    }
    
    int sumNumbers(TreeNode* root) {
        if(root == nullptr)
            return 0;
        
        help(root, 0);
        
        return ret;
    }
};

方法二: 可以用队列存储每一层的节点,然后出队列的同时push 进去新的子孩子。不过在push 子孩子进fifo之前,要更新子孩子的value: root *10 +孩子的数值。 一层层的做下去,到了叶子节点就是最后要的数值。

/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left), right(right) {}
 * };
 */
class Solution {
public:
    int sumNumbers(TreeNode* root) {
        queue<TreeNode*> myq;
        int ret;
        
        myq.push(root);
        
        while(!myq.empty()) {
            int size = myq.size();


            while(size--) {
                root=myq.front();

                myq.pop();
                if(root->left) {
                    root->left->val += root->val * 10;
                    myq.push(root->left);
                }
                if(root->right) {
                    root->right->val += root->val * 10;
                    myq.push(root->right);
                }
                if(root->left == nullptr && root->right == nullptr)
                    ret +=root->val;
            }  
        }
        return ret;
    }
};

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值