Tree

Hello I'm trying to wrap my head around the implementation of a simple binary tree

What I'm trying

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
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
#include <iostream>

using namespace std;

struct bintree {
    int number ;
    char letter ;
    bintree *left = NULL ;
    bintree *right = NULL ;
};

bintree *newNode ( int x, char c ) ;
void printList ( bintree *r) ;
void insertNode (bintree *node, bintree *&r) ;

int main()
{
    bintree *node, *root = NULL ;
    node = newNode (1, 'c') ;
    insertNode ( node, root ) ;
    node = newNode (2, 'e') ;
    insertNode ( node, root ) ;
    node = newNode (3, 'd') ;
    insertNode ( node, root ) ;
    printList (root);
    return 0;
}


bintree *newNode ( int x, char c ) {
    bintree * n = new bintree ;
    n->number = x;
    n->letter = c;
    return n ;
}

void printList ( bintree *r ) {
    cout << r->number << r->letter << endl;
    r = r->right ;
    cout << r->number << r->letter << endl;
    r = r->right ;
    cout << r->number << r->letter << endl;
}

void insertNode (bintree *node, bintree *&r) {
    if (r == NULL)
        r = node ;
    else if (r->left == NULL && r->right == NULL) {
        if (r->number > node->number)
            r->left = node ;
        if ( r->number < node->number)
            r->right = node ;
    else {
        while (r != NULL) {
                if(r->number > node->number)
                    r = r->left;
                else if(r->number < node->number)
                    r = r->right ;
            }
            if (r == NULL)
                r = node;
        }
    }

  }




It crashes when I try to print, I dont think it is inserting the last values into the tree and so when it trys to print a null value it crashes. I'm just curious if I'm heading in the right direction and perhaps how to fix my printing issue as well as some hints on deleting and searching.

Thank you.
t trys to print a null value it crashes
Yes, you need to check whether r is NULL or not in any case before you can use it
Your insertNode() function is incorrect.
You are not linking the new node to the three, and you are moving the root.
Thank you coder777, I will try that.

ne555 can you expand on how I could fix the issue, I see what you mean by moving the root, would I just need to make a different pointer other than the root pointer? I was just treating the r pointer as the root to begin with then as a normal pointer after.
Topic archived. No new replies allowed.