DEV Community

calteen
calteen

Posted on

binary tree

` #include

include

using namespace std;
class Node{
public:
int data;
Node* left;
Node* right;

Node(int data){
this->data = data;
this->left = NULL;
this->right = NULL;

}
};

Node* buildtree(Node* root){
cout<<"plz enter the data"< int data;
cin>>data;
root = new Node(data);

if(data == -1){
return NULL;
}
cout<<"Enter data for inserting into left"< root ->left = buildtree(root->left);
cout<<"Enter data for inserting into right"< root ->right = buildtree(root->right);

return root;

}

void Levelordertraversal(Node* root){
queue q;
q.push(root);

while(!q.empty()){
Node* temp = q.front();
cout<< temp->data<<" ";
q.pop();

  if(temp->left){
  q.push(temp->left);

}
if(temp ->right){
  q.push(temp ->right);
}
Enter fullscreen mode Exit fullscreen mode

}
}

void inorder(Node* root){
//lnr
if(root == NULL){
return;
}

inorder(root->left);
cout<data<< " ";
inorder(root->right);

}
void preorder(Node* root){
//lnr
if(root == NULL){
return;
}
cout<data<< " ";
preorder(root->left);

preorder(root->right);

}
void postorder(Node* root){
if(root == NULL){
return;
}

postorder(root->left);
postorder(root->right);
cout<data<< " ";
}

int main() {
Node* root = NULL;
root = buildtree(root);
//1 3 7 -1 -1 11 -1 -1 5 17 -1 -1 -1
cout<< "inorder traversal :" ;
postorder(root);
return 0;
}`

Top comments (0)