Leetcode刷题笔记题解(C++):257. 二叉树的所有路径

Leetcode刷题笔记题解(C++):257. 二叉树的所有路径_第1张图片

思路:深度优先搜索

/**
 * 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 binaryTreePaths(TreeNode* root) {
        //保存结果
        vector res;
        //进行DFS
        dfs(root,"",res);
        return res;
    }
    void dfs(TreeNode* root,string path,vector& res){
        //当前节点不为空
        if(root!=nullptr){
            //加上节点的值
            path += to_string(root->val);
            //如果当前节点为叶子节点则到头了加入结果并返回
            if(root->left == nullptr && root->right == nullptr){
                res.push_back(path);
                return;
            }
            //当前节点不为空的话则需要向下搜索,左子树和右子树继续深度搜索
            path += "->";
            dfs(root->left,path,res);
            dfs(root->right,path,res);
        }
    }
};

你可能感兴趣的:(Leetcode算法题解,leetcode,笔记,c++)