[Story of BFS and DFS] LC257---all paths of the binary tree (left and right left blank means the end is reached)

The topic is as follows

Insert picture description here

Idea and code

Binary tree, very familiar, or simple binary tree, kill Miao!
The binary tree path can be directly searched by 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)+"->");
    }
};

Guess you like

Origin blog.csdn.net/qq_42136832/article/details/114637431