c_cpp BST实施和遍历
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了c_cpp BST实施和遍历相关的知识,希望对你有一定的参考价值。
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
// #BSTs #BasicProblem
class node{
public:
node* left;
int data;
node* right;
node(){
data=0;
left=NULL;
right=NULL;
}
node(int x){
data=x;
left=NULL;
right=NULL;
}
};
class BST{
public:
node* root;
BST(){
root=NULL;
}
node* BSTinsert(node* root,int x); // Inserts elements to form a BST (l<=n<=r) and returns root
void preOrder(node* root); // Prints the elements of BST in 'pre order'
void inOrder(node* root); // Prints the elements of BST in 'in order'
void postOrder(node* root); // Prints the elements of BST in 'post order'
void levelOrder(node* root); // Prints the elements of BST according the their levels
};
node* BST :: BSTinsert(node* root,int x){
if(root==NULL){
root=new node(x);
}else{
if(x<=root->data){ //if x<root
root->left=BSTinsert(root->left,x); //insert in left branch
}else{
root->right=BSTinsert(root->right,x); //else insert in right branch
}
}
return root;
}
void BST :: preOrder(node* root){ // NLR - Node Left Right
if(root==NULL){
return;
}else{
cout<<root->data<<" ";
preOrder(root->left);
preOrder(root->right);
}
}
void BST :: inOrder(node* root){ // LNR - Left Node Right
if(root==NULL){ // Prints in sorted order if BST is given
return;
}else{
inOrder(root->left);
cout<<root->data<<" ";
inOrder(root->right);
}
}
void BST :: postOrder(node* root){ // LRN - Left Right Node
if(root==NULL){
return;
}else{
postOrder(root->left);
postOrder(root->right);
cout<<root->data<<" ";
}
}
void BST :: levelOrder(node* root){ // Queue is used to print in level order
if(root==NULL){ // 1)8
return; // 2)7 2)9
}else{ // 3)6 3)10
vector<node*> Q;
Q.push_back(root);
while(Q.size()!=0){ // Print until Q is not empty
node* temp=Q[0];
cout<<temp->data<<" ";
if(temp->left!=NULL){
Q.push_back(temp->left); // enqueue left branch if not empty
}
if(temp->right!=NULL){
Q.push_back(temp->right); // enqueue right branch if not empty
}
Q.erase(Q.begin()+0); // dequeue the first node as it is already printed
}
}
}
int main() {
BST t;
int x;
cout<<"No of elements ?"<<endl;
cin>>x;
while(x--){
int n;
cin>>n;
t.root=t.BSTinsert(t.root,n);
}
cout<<"preOrder: ";
t.preOrder(t.root);
cout<<endl;
cout<<"inOrder: ";
t.inOrder(t.root);
cout<<endl;
cout<<"postOrder: ";
t.postOrder(t.root);
cout<<endl;
cout<<"levelOrder: ";
t.levelOrder(t.root);
cout<<endl;
return 0;
}
以上是关于c_cpp BST实施和遍历的主要内容,如果未能解决你的问题,请参考以下文章