recursive binary tree

hey guys, ive got this binary tree program meant to just take in numbers, and output them inorder, but i cant seem to get the print function to work, everything compiles so im lost, a little help would be much appreciated!

heres what i have!

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
#include <iostream>
using namespace std;

struct node* tree = NULL;

struct node { 
    int data; 
    struct node* left; 
    struct node* right; 
};

struct node* newNode(int data) { 
  struct node* tree = new(struct node); 
  tree->data = data; 
  tree->left = NULL; 
  tree->right = NULL;

  return(tree); 
}
  
struct node* insert(struct node* tree, int data) { 
   
  if (tree == NULL) { 
    return(newNode(data)); 
  } 
  else {  
    if (data <= tree->data) 
        tree->left = insert(tree->left, data); 
    else 
        tree->right = insert(tree->right, data);
    return(tree);  
  } 
} 
 

void printTree(struct node* tree) { 
 
    if (tree == NULL) return;
        
  printTree(tree->left); 
  cout << tree->data; 
  printTree(tree->right); 
} 

int main() {
    
    int i;

    do{
        cout << "enter a number into the tree plz.. ";
        cin >> i;
        insert(tree, i);
    }
    while( i != -0);
    
    printTree(tree);

    return 0;
}


thanks again!
You have the variable name 'tree' as a gobal variable and several times as local variable. That's not good but not the problem.

The problem is on line 52. The gobal 'tree' remains NULL while you're producing nodes which are never assigned and hence are lost. Try this: tree = insert(tree, i);
Topic archived. No new replies allowed.