We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
Adding the ifs prevents an extra push to the stack. Why push a null to the stack to check it and immediately return. So, although you could re-write the code:
You have pushed two unnecessary items to the stack for every leaf in the tree and possibly one item to the stack for any branch that has only one child.
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Tree: Preorder Traversal
You are viewing a single comment's thread. Return to all comments →
Adding the ifs prevents an extra push to the stack. Why push a null to the stack to check it and immediately return. So, although you could re-write the code:
void preOrder(node *root){ if(!root) return; printf("%d ", root->data); preOrder(root->left); preOrder(root->right); }
You have pushed two unnecessary items to the stack for every leaf in the tree and possibly one item to the stack for any branch that has only one child.