6
6
#include < structmember.h>
7
7
#include < cstdlib>
8
8
#include < stack>
9
+ #include < queue>
9
10
#include < string>
10
11
#include " ../../../utils/_backend/cpp/utils.hpp"
11
12
#include " ../../../utils/_backend/cpp/TreeNode.hpp"
@@ -158,7 +159,44 @@ static PyObject* BinaryTreeTraversal_depth_first_search(BinaryTreeTraversal* sel
158
159
return BinaryTreeTraversal__post_order (self, Py_BuildValue (" (O)" , node));
159
160
}
160
161
else {
161
- PyErr_SetString (PyExc_NotImplementedError, " This traversal is not implemented yet or does not exist. Supported traversals: \" pre_order\" , \" in_order\" , \" out_order\" " );
162
+ PyErr_SetString (PyExc_NotImplementedError, " This traversal is not implemented yet or does not exist. Supported traversals: \" pre_order\" , \" in_order\" , \" out_order\" , , \" post_order\" " );
163
+ return NULL ;
164
+ }
165
+ }
166
+
167
+ static PyObject* BinaryTreeTraversal_breadth_first_search (BinaryTreeTraversal* self, PyObject *args, PyObject *kwds) {
168
+ Py_INCREF (Py_None);
169
+ PyObject* node = Py_None;
170
+ PyObject* strategy = PyUnicode_FromString (" queue" );
171
+ static char * keywords[] = {" node" ," strategy" , NULL };
172
+ if (!PyArg_ParseTupleAndKeywords (args, kwds, " |OO" , keywords, &node, &strategy)) {
173
+ return NULL ;
174
+ }
175
+ if (PyUnicode_Compare (strategy, PyUnicode_FromString (" queue" )) == 0 ) {
176
+ if (node == Py_None) {
177
+ node = self->tree ->root_idx ;
178
+ }
179
+ std::queue<PyObject*> q;
180
+ PyObject* visit = PyList_New (0 );
181
+ ArrayForTrees* tree = self->tree ->tree ;
182
+ q.push (node);
183
+ while (q.size () > 0 ) {
184
+ node = q.front ();
185
+ q.pop ();
186
+ TreeNode* curr_node = reinterpret_cast <TreeNode*>(tree->_one_dimensional_array ->_data [PyLong_AsLong (node)]);
187
+ PyList_Append (visit, reinterpret_cast <PyObject*>(curr_node));
188
+ if (curr_node->left != Py_None) {
189
+ q.push (curr_node->left );
190
+ }
191
+ if (curr_node->right != Py_None) {
192
+ q.push (curr_node->right );
193
+ }
194
+ }
195
+
196
+ return visit;
197
+ }
198
+ else {
199
+ PyErr_SetString (PyExc_NotImplementedError, " This strategy has not been implemented yet." );
162
200
return NULL ;
163
201
}
164
202
}
@@ -169,6 +207,7 @@ static struct PyMethodDef BinaryTreeTraversal_PyMethodDef[] = {
169
207
{" _out_order" , (PyCFunction) BinaryTreeTraversal__out_order, METH_VARARGS, NULL },
170
208
{" _post_order" , (PyCFunction) BinaryTreeTraversal__post_order, METH_VARARGS, NULL },
171
209
{" depth_first_search" , (PyCFunction) BinaryTreeTraversal_depth_first_search, METH_VARARGS | METH_KEYWORDS, NULL },
210
+ {" breadth_first_search" , (PyCFunction) BinaryTreeTraversal_breadth_first_search, METH_VARARGS | METH_KEYWORDS, NULL },
172
211
{NULL }
173
212
};
174
213
0 commit comments