-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
Krypto wrote:
> 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.
In most implementations I can think of, the limitation on recursion is
more one of stack than of the compiler. One extra flag will consume a
lot less memory than using recursion would.
As I'm sure you know, every time you recurse, a new stack frame is
pushed, containing the arguments to the function &c.
- --
- --Falcon Darkstar Kirtaran
- --
- --OpenPGP: (7902:4457) 9282:A431
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.9 (GNU/Linux)
Comment: Using GnuPG with Mozilla -
http://enigmail.mozdev.org
iQIcBAEBAgAGBQJJdiwcAAoJEKmxP9YxEE4rmHoQAKfhH0VXTZ XDZZkA3zmtQbwo
gA7Tjqwhsius9WTWhgR70rOcIjddzIZqywds/6px1Uqf6sM+dVp1M6aIC2Nh2KwM
DdBPx3soU3Pwzcc2VBIGneefDSgs1C3cK16k/1FIXCQ9vpFr4NaMA/S4QvKGev6T
HBh4OW7NRpuH2DSfP84Q/qYmjuytci5tRl9hj3MT3GcR65zVP4OtpOdTPe9dvsYa
zVufSb9ssL4Cc+K5GJJgIcfrCeV+wl+pO5Tu4IF79nj0GP86IK cSzeG06AOlxmpL
wL45nRWxNy6hWd8ksUxjS/QhprgvQAhl4Zy+PCorE6aaxgjuuwdKrvSKc0u3H36r
IHTChcBB9motW/D2085m0i/fY5DB1EL7KFP6c6cjfVwy+SMbhDeWgX5UxoYE5SqZ
E0Fe75W7BTh7Vvh7POsY25okEuO0DFAs8gWUOCTOP07JddNPuD KPOcfWPQPfZDUl
aBEYCvlEblTC0a7MQz6oW0PTCviHjaSdrTgvglRzWtPG72Ku1t TKBxqLUQ0DWcvQ
NOUoE0y0YLKu5zuvatx0Bt+m6+HoWFx3/7P8fR3BwFZD8OLoNpMAeSw7Eq5qe19L
mhc5GGSDjSr4BPcDBmf6dKZjSHN9IK+TQ5BHd92B0xaHCIthUZ BNjKP4oNMa4yIZ
MhVaFlzWzqC/EjHiTDZx
=wdwa
-----END PGP SIGNATURE-----