Leetcode257. 二叉树的所有路径-代码随想录

目录

题目:

代码(首刷看解析 2024年1月30日):

代码(二刷自解 2024年5月9日 10min bugfree)


题目:


代码(首刷看解析 2024年1月30日):

class Solution {
public:
    void recursion(TreeNode* root,  vector<int>& path, vector<string>& res) {
        path.push_back(root->val);
        if (root->left == nullptr && root->right == nullptr) {
            string spath;
            for (int i = 0; i < path.size() - 1; ++i) {
                spath += to_string(path[i]);
                spath += "->";
            }
            spath += to_string(path[path.size() - 1]);
            res.push_back(spath);
        }
        if (root->left) {
            recursion(root->left,path,res);
            path.pop_back();
        }
        if (root->right) {
            recursion(root->right,path,res);
            path.pop_back();
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<int> path;
        vector<string> res;
        recursion(root,path,res);
        return res;
    }
};

代码(二刷自解 2024年5月9日 10min bugfree)

class Solution {
public:
    // 递归 + 回溯
    vector<string> res;
    void recursion(TreeNode* root, string& path) {
        if (!root->left && !root->right) {
            res.push_back(path);
            return;
        }
        // 前序
        string temp = path;
        if (root->left) {
            path += "->";
            path += to_string(root->left->val);
            recursion(root->left, path);
            path = temp;
        }

        if (root->right) {
            path += "->";
            path += to_string(root->right->val);
            recursion(root->right, path);
            path = temp;
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        res.clear();
        if (!root) return res;
        string path = to_string(root->val);
        recursion(root, path);
        return res;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值