Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
binary tree experiment.
#include <iostream>
struct Node
{
int content;
Node* left;
Node* right;
Node(int,Node*,Node*);
static void add_child(Node* parent, Node* child);
};
Node::Node(int c, Node* l=NULL, Node* r=NULL):content(c),left(l),right(r){}
void Node::add_child(Node* parent, Node* child)
{
if (child-> content <= parent-> content)
{
if (parent-> left == NULL)
{
parent -> left = child;
return;
}
else
{
return Node::add_child(parent-> left, child);
}
}
else
{
if (parent-> right == NULL)
{
parent-> right = child;
return;
}
else
{
return Node::add_child(parent-> right, child);
}
}
}
void inspect_node(Node* node)
{
if (node-> content != NULL)
{
std::cout << node-> content << std::endl;
}
if (node ->left == NULL)
{
std::cout << "Left child null" << std::endl;
}
else
{
std::cout << "Left occupied" << std::endl;
}
if (node ->right == NULL)
{
std::cout << "right child null" << std::endl;
}
else
{
std::cout << "right occupied" << std::endl;
}
}
int main(int argc, const char* argv[])
{
Node* parent_node = new Node(30);
Node* child1 = new Node(20);
Node* child2 = new Node(40);
Node* child3 = new Node(25);
Node::add_child(parent_node, child1);
Node::add_child(parent_node, child2);
Node::add_child(parent_node, child3);
inspect_node(child2);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment