Skip to content

Commit b2f6fa6

Browse files
committed
another DFS implementation
1 parent 065f8e8 commit b2f6fa6

File tree

1 file changed

+37
-1
lines changed

1 file changed

+37
-1
lines changed

‎algorithms/cpp/binaryTreePaths/binaryTreePaths.cpp

+37-1
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
// Source : https://leetcode.com/problems/binary-tree-paths/
2-
// Author : Calinescu Valentin
2+
// Author : Calinescu Valentin, Hao Chen
33
// Date : 2015-10-23
44

55
/***************************************************************************************
@@ -57,3 +57,39 @@ class Solution {
5757
return TreePaths;
5858
}
5959
};
60+
61+
62+
63+
64+
// Another more clear DFS implementation
65+
66+
class Solution {
67+
public:
68+
void binaryTreePathsHelper(TreeNode* root, vector<int> solution, vector<string>& result ) {
69+
if (!root) return;
70+
71+
solution.push_back(root->val);
72+
73+
//meet the leaf node, shape a path into the result
74+
if (root->left==NULL && root->right==NULL){
75+
if(solution.size()>0){
76+
stringstream ss;
77+
for(int i=0; i<solution.size(); i++){
78+
ss << solution[i] << (i<solution.size()-1 ? "->":"");
79+
}
80+
result.push_back(ss.str());
81+
}
82+
return;
83+
}
84+
85+
binaryTreePathsHelper(root->left, solution, result);
86+
binaryTreePathsHelper(root->right, solution, result);
87+
88+
}
89+
vector<string> binaryTreePaths(TreeNode* root) {
90+
vector<string> result;
91+
vector<int> solution;
92+
binaryTreePathsHelper(root, solution, result);
93+
return result;
94+
}
95+
};

0 commit comments

Comments
 (0)