Created
September 28, 2018 13:19
-
-
Save rurumimic/3f8a03312bb0dbb290d56a98b883965e to your computer and use it in GitHub Desktop.
Binary Tree
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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