二叉树的所有路径(leetcode 257

leetcode系列

文章目录

  • 一、核心操作
  • 二、外层配合操作
  • 三、核心模式代码
  • 总结


使用递归法

一、核心操作

1.判断是不是叶子节点(该节点的左右子节点都为空
2.收获该路径(将储存的节点一个一个拿出来,用->连接

if(cur->left==nullptr && cur->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);
            return;
        }

提示:小白个人理解,如有错误敬请谅解!

二、外层配合操作

1.调用递归

三、核心模式代码

代码如下:

class Solution{
public:
    void traversal(TreeNode* cur, vector<int>& path, vector<string>& res)
    {
        path.push_back(cur->val);
        
        if(cur->left==nullptr && cur->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);
            return;
        }
        if(cur->left)
        {
            traversal(cur->left,path,res);
            path.pop_back();//回溯
        }
        if(cur->right)
        {
            traversal(cur->right,path,res);
            path.pop_back();//回溯
        }
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        vector<int> path;
        if(root)traversal(root,path,res);
        return res;
    }
};

精简版代码如下:

class Solution{
public:
    void traversal(TreeNode* cur, string path, vector<string>& res)//path不要引用
    {
        path+=to_string(cur->val);
        if(cur->left==nullptr && cur->right==nullptr)
        {
            res.push_back(path);
            return;
        }
        if(cur->left)traversal(cur->left,path+"->",res);//保证递归调用在收获节点下面,这样才不会多加一个"->",将其作为函数参数传入,可以保证在下层添加的路径不会影响到上层路径
        if(cur->right)traversal(cur->right,path+"->",res);
    }
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> res;
        string path;
        if(root)traversal(root,path,res);
        return res;
    }
};

总结

1.保证递归调用在收获节点下面,这样才不会多加一个"->",将其作为函数参数传入,可以保证在下层添加的路径不会影响到上层路径(因为path没有引用,在每个递归函数里面都是自己独有的path

你可能感兴趣的:(leetcode,linux,算法)