#include<iostream>
#include<queue>
using namespace std;
struct node{
node *l, *r;// * 要跟着变量,指针跟变量类型是平行关系。
int val;
};
node* createRoot(int val);//也可以用来创建一个新节点,返回一个指向这个节点的指针。
bool inst(node *root, int val);
bool del(int val);//未实现
void levelshow(node *r);
int main(){
node *root = createRoot(1);
for(int i = 0; i < 10; i++)
inst(root, i%2);
levelshow(root);
return 0;
}
node* createRoot(int val){
node *root = new node();
root->val = val;
root->l = NULL;
root->r = NULL;
return root;
}
bool inst(node *root, int val){
if(val < root->val){
if(root->l != NULL)
inst(root->l, val);
else{
node *tmp = new node();
tmp->l = NULL;
tmp->r = NULL;
tmp->val = val;
root->l = tmp;
return true;
}
}
else if(val > root->val){
if(root->r != NULL){
inst(root->r, val);
}
else{
node *tmp = new node();
tmp->l = NULL;
tmp->r = NULL;
tmp->val = val;
root->r = tmp;
return true;
}
}
else{
cout << "already exist" << endl;
return false;
}
}
void levelshow(node *root){
queue<node*> q;
q.push(root);
while(!q.empty()){
node *tmp = q.front();
cout << tmp->val << " ";
q.pop();
if(tmp->l != NULL)
q.push(tmp->l);
if(tmp->r != NULL)
q.push(tmp->r);
}
cout << endl;
}
二叉树
最新推荐文章于 2024-07-29 08:47:18 发布