Skip to content

Instantly share code, notes, and snippets.

@vardanator
Created February 20, 2018 02:08
Show Gist options
  • Select an option

  • Save vardanator/bc4771d6c4ef602f8e96aec49df6d135 to your computer and use it in GitHub Desktop.

Select an option

Save vardanator/bc4771d6c4ef602f8e96aec49df6d135 to your computer and use it in GitHub Desktop.
// struct TreeNode {
// T item;
// TreeNode* left;
// TreeNode* right;
// }
// you cann pass a callback function to do whatever you want to do with the node's value
// in this particular example we are just printing its value.
// node is the "starting point", basically the first call is done with the "root" node
void PreOrderTraverse(TreeNode* node)
{
if (!node) return; // stop
std::cout << node->item;
PreOrderTraverse(node->left); // do the same for the left sub-tree
PreOrderTraverse(node->right); // do the same for the right sub-tree
}
void InOrderTraverse(TreeNode* node)
{
if (!node) return; // stop
InOrderTraverse(node->left);
std::cout << node->item;
InOrderTraverse(node->right);
}
void PostOrderTraverse(TreeNode* node)
{
if (!node) return; // stop
PostOrderTraverse(node->left);
PostOrderTraverse(node->right);
std::cout << node->item;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment