Inserting new nodes into a binary tree

I am trying to write an algorithm to insert new nodes into a binary tree. My program crashes and I can't figure out why. My logic and syntax seem correct. Any help is greatly appreciated!

I have a data structure defined as TreeNode. It contains: int key, some other data fields, and TreeNode *left; TreeNode *right; root is a pointer to the root of the tree, it is part of the class MyTree, and newNode is a pointer to a TreeNode structure filled with data and ready to be inserted.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
void MyTree::Insert(TreeNode *newNode)
{

 TreeNode *temp = root; *back = NULL;
//Checking for inserting first node in the tree
if( root == NULL)
{
root = new MyTree(newNode); //this I feel might be the problem but I'm not sure how to fix it.
return;

else //Search for the location in tree to attach the new node
{
while(temp !=NULL)
{
back = temp;
if(temp ->key > newNode->key
temp = temp -> left;
else
temp = temp -> right;
}
//Determine which side to attach the new node to
if(back =NULL)
{
back -> left = newNode;
else
back -> right = newNode;
}
Last edited on
line 6: if statement needs closing bracket on line 10.

What is root?
Yeah, you have no root :-)

Also, you meant to use the comma (,) not semi-colon (;) in line 4,
Line 22 isn't doing what you think (= != ==)

If you think your MyTree constructor or operator new could be the problem then show the code.
Topic archived. No new replies allowed.