Skip to content

Instantly share code, notes, and snippets.

@calebreister
Last active August 29, 2015 14:01
Show Gist options
  • Select an option

  • Save calebreister/af8e84f82f13399dc227 to your computer and use it in GitHub Desktop.

Select an option

Save calebreister/af8e84f82f13399dc227 to your computer and use it in GitHub Desktop.
Simple Binary Tree (in class code)
#include <iostream>
#include <iomanip>
#include <cmath>
#include <stack>
#include <array>
#include <utility>
#include <cstdlib>
#include <ctime>
using namespace std;
class Node {
Node();
int data;
Node* left;
Node* right;
};
Node::Node() {
left = NULL;
right = NULL;
}
//Depth of a tree: starts at 0
class BinTree {
private:
Node* root = NULL;
void printNodeInOrder(Node* n);
void delNode(Node* n);
public:
void insert(int data);
void printInOrder();
};
int main() {
BinTree test;
test.insert(50);
test.insert(55);
test.insert(45);
test.insert(23);
test.insert(85);
test.insert(53);
test.printInOrder();
}
void BinTree::insert(int data) {
Node* nn = new Node;
nn->data = data;
if (root == NULL)
{
root = nn;
return;
}
else
{
Node* current = root;
Node* parent;
//find the parent of nn
while (current != NULL)
{
parent = current;
if (nn->data < current->data)
current = current->left;
else if (nn->data > current->data)
current = current->right;
else
{
delete nn;
return;
}
}
//adjust parent pointers
if (nn->data < parent->data)
parent->left = nn;
else
parent->right = nn;
}
}
void BinTree::printNodeInOrder(Node* n) {
if (n != NULL)
{
printNodeInOrder(n->left);
cout << n->data << '\n';
printNodeInOrder(n->right);
}
}
void BinTree::printInOrder() {
printNodeInOrder(root);
}
void BinTree::delNode(Node* n) {
if (n != NULL)
{
delNode(n->left);
delNode(n->right);
delete n;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment