240
笔下虽有千言,胸中实无一策

30 Day Challenge Day 15 | Leetcode 257. Binary Tree Paths

题解

Easy | DFS

class Solution {
public:
    vector<string> binaryTreePaths(TreeNode* root) {
        vector<string> paths;
        dfs(root, "", paths);
        return paths;
    }
    
    void dfs(TreeNode* node, string path, vector<string>& paths) {
        if(!node) return;
        
        if(!node->left && !node->right) {
            path += to_string(node->val);
            paths.push_back(path);
            return;
        }
        
        path += to_string(node->val) + "->";

        dfs(node->left, path, paths);
        dfs(node->right, path, paths);
    }
};
posted @ 2020-09-30 14:53  CasperWin  阅读(67)  评论(0编辑  收藏  举报