Below I have attached my code. In the below code I am building a binary tree with 3 nodes. My program is printing different values at same address when passed in different function. And there are 4 functions in total
- main
- build
- inorder
in the inorder function, I am doing the inorder traversal of the tree and saving that in a vector<Node*> so later I can print the inorder traversal in the "print" function. I am printing the address and the value at each address in all the 4 functions. Getting different values in some functions at the same address. Why is that so?
#include <bits/stdc++.h>
using namespace std;
struct Node
{
int data;
Node *left;
Node *right;
Node(int val)
{
data = val;
left = right = NULL;
}
};
Node *build()
{
Node *root = new Node(50);
root->left = new Node(45);
root->right = new Node(60);
cout << "In Build Function\n";
cout << root << " " << root->data << endl;
cout << root->left << " " << root->left->data << endl;
cout << root->right << " " << root->right->data << endl;
return root;
}
void inorder(Node *root, vector<Node *> &A)
{
if (root == NULL)
return;
inorder((root)->left, A);
free(root->left);
A.push_back(root);
cout << root << " " << root->data << endl;
inorder(root->right, A);
free(root->right);
}
void print(vector<Node *> &A)
{
cout << "\nprint in function\n";
for (int i = 0; i < A.size(); i++)
cout << A[i] << " " << A[i]->data << endl;
cout << endl;
}
int main()
{
Node *root = build();
cout << "\nIn Main Function\n";
cout << root << " " << root->data << endl;
cout << root->left << " " << root->left->data << endl;
cout << root->right << " " << root->right->data << endl;
vector<Node *> A;
cout << "\nIn inorder Function\n";
inorder(root, A);
print(A);
cout << "\nIn Main Function\n";
cout << root << " " << root->data << endl;
cout << root->left << " " << root->left->data << endl;
cout << root->right << " " << root->right->data << endl;
}
output :
In Build Function
0x1d6bc0 50
0x1d6bd8 45
0x1d6bf0 60
In Main Function
0x1d6bc0 50
0x1d6bd8 45
0x1d6bf0 60
In inorder Function
0x1d6bd8 45
0x1d6bc0 50
0x1d6bf0 60
print in function
0x1d6bd8 1928224
0x1d6bc0 50
0x1d6bf0 60
In Main Function
0x1d6bc0 50
0x1d6bd8 1928224
0x1d6bf0 60