r/programminghelp • u/Luffysolos • Oct 24 '22
C++ New to Binary Trees
Ok so i just started learning Binary trees. The problem im having is my print function wont give me the output of the values in the left side of the binary tree. Can someone tell me how I can get the ouput i want?
#include <cstdlib>
#include <iostream>
#include <string>
#include <ctime>
using namespace std;
struct Node{ // That Binary Tree
int data;
Node* right;
Node* left;
};
Node* createNode(int data){
Node* newNode = new Node();
newNode->data = data;
newNode->left = newNode-> right = nullptr;
return newNode;
}
void PrintNumbers(Node* root){
if(root = nullptr) return;
cout<<root->data <<endl;
PrintNumbers(root->left);
PrintNumbers(root->right);
}
int main(){
srand(time(0));
// Random list of numbers
Node* root=NULL;
int Small0 = 1 + rand() % 3;
int Small1 = 1 + rand() % 3;
int small2 = 1 + rand() % 3;
int small3 = 1 + rand() % 3;
int small4 = 1 + rand() % 3;
int small5 = 1 + rand() % 3;
root->left = createNode(Small0);
root->left = createNode(Small1);
root->left = createNode(small2);
root->left = createNode(small3);
root->left = createNode(small4);
root->left = createNode(small5);
PrintNumbers(root);
}
Output i get
zsh: segmentation fault
3
Upvotes
1
u/Luffysolos Oct 24 '22
Amazing. I also have another question. How would you insert data into a parent node?