This is my clumsy implementation of insertion into a binary tree class. It just uses nested "if" statement to walk through the node recursively.
Tree insertion seems to work better if it takes in as the argument the pointer to a node. But since the node is private, it makes recursion call a lot more awkward through the use of a member variable "temp_insert" to walk around the nodes. is there a way to avoid this problem?Code:class Tree { private: struct Node { int item; // relate[0] = parent; // relate[1] = left child; // relate[2] = right child; Node * relate[3]; Node(int n = 0):item(n) { relate[0]=relate[1] = relate[2] = 0; } }; Node* root, *temp_insert; public: void insert_tree(int x); }; // insertion void Tree::insert_tree(int x) { if ( x < temp_insert->item) { if( temp_insert->relate[1] != NULL) { temp_insert = temp_insert->relate[1]; insert_tree(x); } else { Node * temp = new Node(x); temp_insert->relate[1] = temp; temp->relate[0] = temp_insert; temp_insert = root; } } else if( x > temp_insert->item ) { if( temp_insert->relate[1] != NULL) { temp_insert = temp_insert->relate[2]; insert_tree(x); } else { Node * temp = new Node(x); temp_insert->relate[2] = temp; temp->relate[0] = temp_insert; temp_insert = root; } } }