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
2
u/eatmorepies23 Oct 24 '22 edited Oct 25 '22
First: root is null when createNode is executed. You set it to null at the beginning of your main function, and you don't give it a value later on. Therefore, root->left returns null, which throws an error.
Second: In regards to the print function, PrintNumbers doesn't correctly check if root was nullptr. You need to use ==, which compares root to nullptr. '=' sets root to nullptr, so you will have an error if you try to access its value.
The rest of your code looks fine, assuming your intent is to simply overwrite root->left. You aren't adding anything to the tree with those; you're just replacing what's there.
Edit: Adjusted formatting
2
u/link3333 Oct 24 '22
Love the response from /u/eatmorepies23.
Unimportant nitpick on
PrintNumbers:rootdoesn't seem like an appropriate argument name. It's a recursive method that would really only operate on the root node once. Probably rename tonode. There could be functions where you do actually want the root, but here it doesn't matter.