File tree 1 file changed +37
-1
lines changed
algorithms/cpp/binaryTreePaths
1 file changed +37
-1
lines changed Original file line number Diff line number Diff line change 1
1
// Source : https://leetcode.com/problems/binary-tree-paths/
2
- // Author : Calinescu Valentin
2
+ // Author : Calinescu Valentin, Hao Chen
3
3
// Date : 2015-10-23
4
4
5
5
/* **************************************************************************************
@@ -57,3 +57,39 @@ class Solution {
57
57
return TreePaths;
58
58
}
59
59
};
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
+ };
You can’t perform that action at this time.
0 commit comments