K
Krypto
I am writing binary tree programs using non-recursion and recursion to
understand the differences and pros and concs. Here, I am trying to do
a post-order traversal using recursion and non-recusion.
While I can write recusive version more simplistically, for writing
the non-recusive I have to store an extra state called visited.
Here is my code for non recusive.
typedef node {
int data;
node *left;
node *right;
int visited = 0;
} node;
/*
Assuming you have a stack setup with push() and pop() operations.
Also assuming that all nodes are initially marked to 0.
(This function will reset them back to zero when finished)
*/
void postorder(Node *n) {
push(n);
while (stack.size > 0) {
n = (Node*)pop();
if (n->marked || (n->left == NULL && n->right == NULL)) {
n->marked = 0;
printf("%d\n", n->value);
}
else {
n->marked = 1;
push(n);
if (n->right) push(n->right);
if (n->left) push(n->left);
}
}
}
And this is my recusive version which is lot simpler and elegant.
void postorder( node *node){
if (node){
postorder(node->left);
postorder(node->right);
printf("%d", node->data);
} else
return;
}
Can you please tell me if we can even write a non-recusive function
without the extra flag visited. I want to minimize the extra overhead.
When should we use recusion and when should we not ? What is the
maximum recursion depth of a gcc compiler ? I am trying to learn to
write better code and these are the questions which are not answered
in my mind. Please help.
understand the differences and pros and concs. Here, I am trying to do
a post-order traversal using recursion and non-recusion.
While I can write recusive version more simplistically, for writing
the non-recusive I have to store an extra state called visited.
Here is my code for non recusive.
typedef node {
int data;
node *left;
node *right;
int visited = 0;
} node;
/*
Assuming you have a stack setup with push() and pop() operations.
Also assuming that all nodes are initially marked to 0.
(This function will reset them back to zero when finished)
*/
void postorder(Node *n) {
push(n);
while (stack.size > 0) {
n = (Node*)pop();
if (n->marked || (n->left == NULL && n->right == NULL)) {
n->marked = 0;
printf("%d\n", n->value);
}
else {
n->marked = 1;
push(n);
if (n->right) push(n->right);
if (n->left) push(n->left);
}
}
}
And this is my recusive version which is lot simpler and elegant.
void postorder( node *node){
if (node){
postorder(node->left);
postorder(node->right);
printf("%d", node->data);
} else
return;
}
Can you please tell me if we can even write a non-recusive function
without the extra flag visited. I want to minimize the extra overhead.
When should we use recusion and when should we not ? What is the
maximum recursion depth of a gcc compiler ? I am trying to learn to
write better code and these are the questions which are not answered
in my mind. Please help.