I'm new in binary tree, i want to traverse the 2 node in the binary tree but the output result into a random number or no output.
Here's the driver function:
int main(){
node *root, *num2;
bt tree;
root = new node;
root->data = 12;
root->left = num2;
root->right = NULL;
tree.root = root;
num2 = new node;
num2->data = 10;
num2->right = NULL;
num2->left =NULL;
std::cout<<"Postorder: ";
tree.postorder();
std::cout<<"\n";
return 0;
}
Binary traversal methods:
struct bt{
node *root = nullptr;
public:
void postorder(){
postorder_impl(root);
}
private:
void postorder_impl(node *start){
if(!start) return;
postorder_impl(start->left);
postorder_impl(start->right);
std::cout << start->data << " ";
}
};
CodePudding user response:
When you write root->left = num2;
num2
is uninitalized yet. So it is a random adres in memory. So root->left
(and start->left
inside the postorder();
function). So you will call the postorder_impl();
function with an undefined adress will be is a random memoryadres even after you set num2 to a valid node.
Put num2 = new node;
before it. root->left = num2;