6
6
#include < structmember.h>
7
7
#include < cstdlib>
8
8
#include < iostream>
9
+ #include < stack>
9
10
#include " ../../../utils/_backend/cpp/utils.hpp"
10
11
#include " ../../../utils/_backend/cpp/TreeNode.hpp"
11
12
#include " ../../../linear_data_structures/_backend/cpp/arrays/ArrayForTrees.hpp"
@@ -24,13 +25,14 @@ static void BinaryTreeTraversal_dealloc(BinaryTreeTraversal *self) {
24
25
25
26
static PyObject* BinaryTreeTraversal___new__ (PyTypeObject* type, PyObject *args, PyObject *kwds) {
26
27
BinaryTreeTraversal *self;
28
+ self = reinterpret_cast <BinaryTreeTraversal*>(type->tp_alloc (type, 0 ));
29
+
27
30
PyObject* tree = PyObject_GetItem (args, PyZero);
28
31
if (PyType_Ready (&BinarySearchTreeType) < 0 ) { // This has to be present to finalize a type object. This should be called on all type objects to finish their initialization.
29
32
return NULL ;
30
33
}
31
34
if (PyObject_IsInstance (tree, (PyObject *)&BinarySearchTreeType)) {
32
35
self->tree = reinterpret_cast <BinarySearchTree*>(tree)->binary_tree ;
33
- std::cout<<" here" <<std::endl;
34
36
}
35
37
else {
36
38
PyErr_SetString (PyExc_ValueError, " Not a supported type for BinaryTreeTraversal." );
@@ -39,7 +41,31 @@ static PyObject* BinaryTreeTraversal___new__(PyTypeObject* type, PyObject *args,
39
41
return reinterpret_cast <PyObject*>(self);
40
42
}
41
43
44
+ static PyObject* BinaryTreeTraversal__pre_order (BinaryTreeTraversal* self, PyObject *args){
45
+ PyObject* visit = PyList_New (0 );
46
+ ArrayForTrees* tree = self->tree ->tree ;
47
+ long size = self->tree ->size ;
48
+ long node = PyLong_AsLong (PyObject_GetItem (args, PyZero));
49
+ std::stack<long > s;
50
+ s.push (node);
51
+
52
+ while (!s.empty ()) {
53
+ node = s.top ();
54
+ s.pop ();
55
+ TreeNode* curr_node = reinterpret_cast <TreeNode*>(tree->_one_dimensional_array ->_data [node]);
56
+ PyList_Append (visit, reinterpret_cast <PyObject*>(curr_node));
57
+ if (curr_node->right != Py_None) {
58
+ s.push (PyLong_AsLong (curr_node->right ));
59
+ }
60
+ if (curr_node->left != Py_None) {
61
+ s.push (PyLong_AsLong (curr_node->left ));
62
+ }
63
+ }
64
+ return visit;
65
+ }
66
+
42
67
static struct PyMethodDef BinaryTreeTraversal_PyMethodDef[] = {
68
+ {" _pre_order" , (PyCFunction) BinaryTreeTraversal__pre_order, METH_VARARGS, NULL },
43
69
{NULL }
44
70
};
45
71
0 commit comments