void binaryTreePathsDFS(TreeNode *curNode, vector<TreeNode *> &path, vector<string> &res) { // terminating condition if (curNode->left == NULL && curNode->right == NULL) { // convert path into string string s = ""; int i; for (i = 0; i < path.size()-1; i++) { s += to_string(path[i]->val) + "->"; } s += to_string(path[i]->val); res.push_back(s); return; } // DFS step if (curNode->left) { path.push_back(curNode->left); binaryTreePathsDFS(curNode->left, path, res); path.pop_back(); } if (curNode->right) { path.push_back(curNode->right); binaryTreePathsDFS(curNode->right, path, res); path.pop_back(); } }
//depth first travers void binaryTreePathsDFS(TreeNode *root, string out, vector<string> &paths) { if (!root->left && !root->right) paths.push_back(out); if (root->left) { binaryTreePathsDFS(root->left, out + "->" + to_string(root->left->val), paths); } if (root->right) { binaryTreePathsDFS(root->right, out + "->" + to_string(root->right->val), paths); } }
vector<string> binaryTreePaths(TreeNode* root) { vector<string> res; if (!root) return res; vector<TreeNode *> path; path.push_back(root); binaryTreePathsDFS(root, path, res); return res; }
vector<string> binaryTreePaths(TreeNode* root) { vector<string> paths; if (!root) return paths; binaryTreePathsDFS(root, to_string(root->val), paths); return paths; }