struct BSTreeNode
{
struct BSTreeNode *leftchild;
AnsiString data;
struct BSTreeNode *rightchild;
};
struct BSTreeNode * root;
String tree = "";
struct BSTreeNode * newNode(AnsiString x)
{
struct BSTreeNode * node = new struct BSTreeNode;
node->data = x;
node->leftchild = NULL;
node->rightchild = NULL;
return node;
}
struct BSTreeNode * insertBSTree(struct BSTreeNode * node , AnsiString x)
{ if(node == NULL) return newNode(x);
if(x < node->data)
node->leftchild = insertBSTree(node->leftchild, x);
else
node->rightchild = insertBSTree(node->rightchild, x);
return node;
}
void printBSTree(struct BSTreeNode * node)
{ if(node != NULL)
{ printBSTree(node->leftchild);
tree += node->data+"_";
printBSTree(node->rightchild);
}
}
//--- insert button ---
void __fastcall TForm1::Button1Click(TObject *Sender)
{
AnsiString data;
data = Edit1->Text;
root = insertBSTree(root, data);
tree = "";
printBSTree(root);
Memo1->Lines->Add(tree);
}
Supposed that I insert A、B、C、D、E、F、G into the binary tree(Button1Click is the button to insert data into the binary tree) the binary tree should be like
A
/ \
B C
/ \ / \
H J D E
/ \
F G
but it turned out to be like
A
\
B
\
C
\
D
\
E
\
F
\
G
struct BSTreeNode ---> tree node
struct BSTreeNode * newNode(AnsiString x) ---> creating a new node
button1Click ---> insert the data from Edit->text; to the binary tree.
insertBSTree ---> if the node is null, then create a new node. Inserting the data into the leftchild/rightchild
You've created a binary search tree when you use
<to determine which branch to insert into:Your second example is a binary search tree, just not a balanced one.
Your expected result cannot be created by the functions shown because they maintain a strict invariant where the left branch must only contain values less than the root. The efficiency involved in a binary search tree only applies to balanced ones.
A balanced binary search tree containing this data would look like the following, because all trees involved (including subtrees) are balanced.
You can get to this by adding a mechanism to check if your tree is balanced, and making adjustments by "rotating" trees left or right.
Becomes balanced, by rotating left around the smallest value on the right side of the tree.
To balance your initial tree:
You'd check each subtree to see if it's balanced. The first subtree that is unbalanced is E, F, G.
We'd then see that D, E, F, G is unbalanced to the right.
And so on...
If we go another few steps further: