leetcode 129. 求根节点到叶节点数字之和

2023.9.8

leetcode 129. 求根节点到叶节点数字之和_第1张图片

        好久没写回溯题了,有点陌生ToT。 

        本题思路就是通过回溯保存所有根节点到叶子节点的路径,然后将这些路径转化为数字并全部相加。 直接看代码:

/**
 * 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 {
private:
    vector path;
    int ans;
    //将保存的路径值转化为数字
    int path2sum(vector& path)
    {
        int sum = 0;
        for(int i=0; ileft && !cur->right)
        {
            ans += path2sum(path);
            return;
        }
        if(cur->left)
        {
            path.push_back(cur->left->val);
            backtrating(cur->left);
            path.pop_back();
        }
        if(cur->right)
        {
            path.push_back(cur->right->val);
            backtrating(cur->right);
            path.pop_back();
        }
    }
public:
    int sumNumbers(TreeNode* root) {
        path.push_back(root->val);
        backtrating(root);
        return ans;
    }
};

你可能感兴趣的:(leetcode专栏,leetcode,算法,cpp,数据结构)