Open
Description
void binaryTreePaths(vector<string>& result, TreeNode* root, string t) {
if(!root->left && !root->right) {
result.push_back(t);
return;
}
if(root->left) binaryTreePaths(result, root->left, t + "->" + to_string(root->left->val));
if(root->right) binaryTreePaths(result, root->right, t + "->" + to_string(root->right->val));
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> result;
if(!root) return result;
binaryTreePaths(result, root, to_string(root->val));
return result;
}
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
void dfs(TreeNode* root, string& path, vector<string>& v){
auto t = path;
path += "->" + to_string(root->val);
if(root->left == nullptr && root->right == nullptr){
v.push_back(path);
}
if(root->left != nullptr){
dfs(root->left, path, v);
}
if(root->right != nullptr){
dfs(root->right, path, v);
}
path = t;
}
vector<string> binaryTreePaths(TreeNode* root) {
vector<string> v;
if(root == nullptr) return v;
string path = to_string(root->val);
if(root->left == nullptr && root->right == nullptr) v.push_back(path);
if(root->left) dfs(root->left, path, v);
if(root->right) dfs(root->right, path, v);
return v;
}
};