C++ simple DFS solution


  • 0
    H
    class Solution {
    public:
        void dfs(TreeNode* root, string cur, vector<string>& ans) {
            if(cur == "") cur = cur + to_string(root->val);
            else cur = cur + "->" + to_string(root->val);
            if(!root->left && !root->right) ans.push_back(cur);
            if(root->left) dfs(root->left, cur, ans);
            if(root->right) dfs(root->right, cur, ans);
        }
        vector<string> binaryTreePaths(TreeNode* root) {
            if(!root) return vector<string> ();
            vector<string> ans;
            dfs(root, "", ans);
            return ans;
        }
    };
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.