[BFS和DFS的故事]LC257---二叉树的所有路径(左右为空说明走到尽头了)

题目如下

在这里插入图片描述

思路与代码

二叉树,很熟悉,还是简单的二叉树,缪杀!
二叉树路径直接dfs深搜就可以了啊!

/**
 * 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 {
    
    
public:
    vector<string> ans;
    vector<string> binaryTreePaths(TreeNode* root) {
    
    
        string path;
        dfs(root,path);
        return ans;
    }
    void dfs(TreeNode* root,string path){
    
    
        if(!root) return;
        if(!root->left&&!root->right){
    
    
            ans.push_back(path+to_string(root->val));
            return ;
        }
        if(root->left) dfs(root->left,path+to_string(root->val)+"->");
        if(root->right) dfs(root->right,path+to_string(root->val)+"->");
    }
};

猜你喜欢

转载自blog.csdn.net/qq_42136832/article/details/114637431
今日推荐