【Leetcode二叉树属性六】257. 二叉树的所有路径

Leetcode257

1.问题描述

在这里插入图片描述

2.解决方案

解法一:递归

总结

本道题一看收集节点信息这种就想到要使用递归回溯,那么直接上回溯模板
1.递归出口,如果遇到空结点直接return回溯就好,如果遇到叶子节点那么就需要收集一下结果

if(root== nullptr){
    //ans.push_back(string(path.begin(),path.end()-2));
    return;
}
if(root->left== nullptr&&root->right== nullptr){
    //path.push_back(char(root->val+48));
    path+= to_string(root->val);
    ans.push_back(path);
    return;
}

2.由于需要回溯所以把记录路径的path设置为了函数参数,这样就起到了回溯的效果,递归完左子树,到递归右子树的时候path还只是root没有变化,这就代表发生了回溯,尽管不是显式的

backtracking(root->left,path);
backtracking(root->right,path);

3.就是收集路径过程使用的数据结构这个也得好好考虑,首先path使用string类型,收集的时候直接用+来合并字符串没毛病,然后就是把数组转化成char或者string合并的时候,一开始使用了path.push_back(char(root->val+48)),发现如果是负数就不对了,这下清楚了以后直接to_string()!


代码:
class Solution {
public:
    vector<string> ans;
    //string path;
    void backtracking(TreeNode* root,string path){
        if(root== nullptr){
            //ans.push_back(string(path.begin(),path.end()-2));
            return;
        }
        if(root->left== nullptr&&root->right== nullptr){
            //path.push_back(char(root->val+48));
            path+= to_string(root->val);
            ans.push_back(path);
            return;
        }
        //path.push_back(char(root->val+48));
        //path.push_back('-');
        //path.push_back('>');
        path+= to_string(root->val);
        path+= "->";
        backtracking(root->left,path);
        backtracking(root->right,path);
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        string path;
        backtracking(root,path);
        return ans;
    }
};


解法二:迭代

就是利用统一迭代前序遍历模拟遍历路径的过程
又涉及到那个统一迭代法,这个我还没看

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值