Binary Tree Not Printing

I cannot figure out why my binary tree is not printing.

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
69
70
71
72
73
74
#include <iostream>

using namespace std ;

struct treeNode {
  
  int data ;
  treeNode * left = NULL ;
  treeNode * right = NULL ;
  
} ;

void createNode ( treeNode * root , int toInsert) ;

void displayTree ( treeNode * root , int level = 0 ) ;

int main ( ) {
  
  treeNode * treeRoot = new treeNode ;
  treeRoot->data = 5 ;
  createNode ( treeRoot , 4 ) ;
  createNode ( treeRoot , 2 ) ;
  createNode ( treeRoot , 8 ) ;
  createNode ( treeRoot , 12 ) ;
  createNode ( treeRoot , 50 ) ;
  
  displayTree ( treeRoot ) ;
  
  return 0 ;
  
}

void createNode ( treeNode * root , int toInsert ) {
  
  if ( root == NULL ) {
	
	root = new treeNode ;
	root->data = toInsert ;
	
  }
  
  else {
	
	if ( toInsert > root->data )
	  createNode ( root->right , toInsert ) ;
	  
	else if ( toInsert > root->data , toInsert )
	  createNode ( root->left , toInsert ) ;
	
  }
  
}



void displayTree ( treeNode * root , int level ) {
  
  if ( !root ) {
	
	cout << "Tree Is Empty\n" ;
	
  }
  
  else {

    displayTree ( root->left , level ) ;

    level ++ ;
    cout << "Level: " << level << "Value: " << root->data << endl ;

    displayTree ( root->right , level ) ;
  }
  
}
You have to fix to things.
Definition of createNode function must be void createNode ( treeNode *&root , int toInsert ). You must pass pointer by reference.

And
1
2
3
4
5
6
7
8
9
  else {
	
	if ( toInsert > root->data ) // this is correct
	  createNode ( root->right , toInsert ) ;
// this line is identical to previous one. Change > to <. And remove ", toInsert"	  
	else if ( toInsert > root->data , toInsert ) 
	  createNode ( root->left , toInsert ) ;
	
  }
Last edited on
Topic archived. No new replies allowed.