The basic idea is to start from root
and add it to the current path
, then we recursively visit its left
and right
subtrees if they exist; otherwise, we have reached a leaf node, so just add the current path
to the result paths
.
The code is as follows.
1 class Solution { 2 public: 3 vectorbinaryTreePaths(TreeNode* root) { 4 vector paths; 5 string path; 6 treePaths(root, path, paths); 7 return paths; 8 } 9 private:10 void treePaths(TreeNode* node, string path, vector & paths) {11 if (!node) return;12 path += path.empty() ? to_string(node -> val) : "->" + to_string(node -> val);13 if (!(node -> left) && !(node -> right)) {14 paths.push_back(path);15 return;16 }17 if (node -> left) treePaths(node -> left, path, paths);18 if (node -> right) treePaths(node -> right, path, paths);19 }20 };