[dfs]leetcode257:二叉树的所有路径(easy)

题目:
在这里插入图片描述
题解:

  • 经典的dfs框架,大家直接看代码即可。

代码如下:

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        if(!root)return {};
        vector<string> res;
        helper(root,res,"");
        return res;
    }

    void helper(TreeNode* root,vector<string>& res,string trace)
    {
        //1、递归边界
        if(root==nullptr)return;
        //2、递归表达式
        trace+=to_string(root->val);
        //3、寻找到一个可行解,即达到叶子节点,dfs结束
        if(root->left==nullptr&&root->right==nullptr){
            res.push_back(trace);
            return;
        }
        //4、继续进行dfs
        if(root->left)helper(root->left,res,trace+"->");
        if(root->right)helper(root->right,res,trace+"->");
    }
};
发布了484 篇原创文章 · 获赞 149 · 访问量 11万+

猜你喜欢

转载自blog.csdn.net/qq_43152052/article/details/103739857
今日推荐