Skip to content

Instantly share code, notes, and snippets.

@rurumimic
Created September 28, 2018 13:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rurumimic/3f8a03312bb0dbb290d56a98b883965e to your computer and use it in GitHub Desktop.
Save rurumimic/3f8a03312bb0dbb290d56a98b883965e to your computer and use it in GitHub Desktop.
Binary Tree
#include <iostream>
using namespace std;
struct node {
int key;
int size;
node *left;
node *right;
node(const int& _key) :
key(_key), size(1), left(NULL), right(NULL) {}
void setLeft(node* newNode) { left = newNode; calSize(); }
void setRight(node* newNode) { right = newNode; calSize(); }
void calSize() {
size = 1;
if (left) size += left->size;
if (right) size += right->size;
};
};
void inOrder(node *n) {
if (n->left) {
inOrder(n->left);
}
cout << n->key << endl;
if (n->right) {
inOrder(n->right);
}
}
void preOrder(node *n) {
cout << n->key << endl;
if (n->left) {
preOrder(n->left);
}
if (n->right) {
preOrder(n->right);
}
}
void postOrder(node *n) {
if (n->left) {
postOrder(n->left);
}
if (n->right) {
postOrder(n->right);
}
cout << n->key << endl;
}
int main(int argc, const char * argv[]) {
node *node5 = new node(5);
node *node3 = new node(3);
node *node1 = new node(1);
node *node2 = new node(2);
node2->setLeft(node1);
node2->setRight(node3);
node *node4 = new node(4);
node4->setLeft(node2);
node4->setRight(node5);
cout << "InOrder" << endl;
inOrder(node4);
cout << "PreOrder" << endl;
preOrder(node4);
cout << "PostOrder" << endl;
postOrder(node4);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment