I just wanted to implement a TreeNode class that works similar to that of a struct node for a tree implementation.
Everything is working fine except for the output that is including 0 at the beginning of the inOrder traversal. Can anyone please explain it to me why is that happening?
Input:
22,1,2,3,5,4,11,20,19,24,21
Output:
0 1 2 3 4 5 11 19 20 21 22 24
#include <bits/stdc++.h>
using namespace std;
class TreeNode{
public:
int data;
TreeNode* left;
TreeNode* right;
TreeNode(){
left = NULL;
right = NULL;
}
TreeNode(int val){
data = val;
left = NULL;
right = NULL;
}
};
void insertInorder(TreeNode* cur, int d){
if(d <= cur->data){
if(cur->left == NULL)
cur->left = new TreeNode(d);
else
insertInorder(cur->left,d);
}
else{
if(cur->right == NULL)
cur->right = new TreeNode(d);
else
insertInorder(cur->right,d);
}
}
TreeNode* makeTree(vector<int> v){
TreeNode* root = NULL;
for(int start = 0; start <= v.size(); start++){
if(start == 0){
root = new TreeNode();
root->data = v[0];
}
insertInorder(root,v[start]);
}
return root;
}
void printInorder(TreeNode* node)
{
if (node == NULL)
return;
/* first recur on left child */
printInorder(node->left);
/* then print the data of node */
cout << node->data << " ";
/* now recur on right child */
printInorder(node->right);
}
int main(){
vector<int> x = {22,1,2,3,5,4,11,20,19,24,21};
TreeNode* r = makeTree(x);
printInorder(r);
return 0;
}
Edit:
To the people visiting this questions at a future date. Better practices states that we shouldn't use
#include <bits/stdc++.h>
using namespace std;
Using namespace std can result into future namespace collisions in the code. For reference here. I did the same mistake but I won't be doing this from now on.
Please refer to the link provided by @Jabberwocky here