//二叉树的存储结构
struct node {
typename data;
int layer;
node* lchild;
node* rchild;
};
node* root = NULL;
//建立新结点
node* newNode(int v) {
node* Node = new node;
Node->data = v;
Node->lchild = Node->rchild = NULL;
return Node;
}
//二叉树结点的查找、修改
void search(node* root, int x, int newdata) {
if(root == NULL) {
return;
}
if(root->data == x) {
root->data = newdata;
}
search(root->lchild, x, newdata);
search(root->rchild, x, newdata);
}
//二叉树结点的插入
//insert函数将在二叉树中插入一个数据域为x的新结点
//注意跟结点指针root要使用引用,否则会插入不成功
//如果函数中需新建结点,即对二叉树结构做出修改,就需要加引用;
//如果只是修改当前已有结点的内容或遍历树,不需加引用
void insert(node* &root, int x) {
if( root == NULL ) {
root = newNode(x);
return;
}
if(条件成立) {
insert(root->lchild, x);
} else {
insert(root->rchild, x);
}
}
//二叉树的建立
node* create(int data[], int n) {
node* root = NULL;
for(int i=0; i<n; i++) {
insert(root, data[i]);
}
return root;
}
//先序遍历(根结点--左子树--右子树)
void preOrder(node* root) {
if(root == NULL) {
return;
}
printf("%d\n", root->data);
preOrder("%d\n", root->lchild);
preOrder("%d\n", root->rchild);
}
//中序遍历(左子树--根节点--右子树)
void inOrder(node* root) {
if(root == NULL) {
return;
}
inOrder(root->lchild);
printf("%d\n", root->data);
inOrder(root->rchild);
}
//后序遍历(左子树--右子树--根节点)
void postOrder(node* root) {
if(root == NULL) {
return;
}
postOrder(root->lchild);
postOrder(root->rchild);
printf("%d\n", root->data);
}
//层序遍历(广搜)
void LayerOrder(node* root) {
queue<ndoe*> q;
q.push(root);
while( !q->empty() ) {
node* now = q->front();
q.pop();
printf("%d", now->data);
if(now->lchild != NULL) q.push(now->lchild);
if(now->rchild != NULL) q.push(now->rchild);
}
}
//层序遍历(加入layer)
void LayerOrder(node* root) {
queue<node*> q;
root->layer = 1;
q.push(root);
while( !q->empty() ) {
node* now = q->front();
q.pop();
printf("%d ", now->data);
if( now->lchild != NULL) {
now->lchild->layer = now->layer + 1;
q.push(now->lchild);
}
if( now->rchild != NUll) {
now->rchild->layer = now->layer + 1;
q.push(now->rchild);
}
}
}
//已知先序遍历和中序遍历,重建二叉树
node* create(int preL, int preR, int inL, int inR) {
if(preL > preR) {
return NULL;
}
node* root = new node;
root->data = pre[preL];
int k;
for(k=inL; k<=inR; k++) {
if(pre[preL]==in[k])
break;
}
int numLeft = k - inL;
root->lchild = create(preL+1, preL+numLeft, inL, k-1);
root->rchild = creatr(preL+numLeft+1, preR, k+1, inR);
return root;
}
//已知后序遍历和中序遍历,重建二叉树
node* create(int postL, int postR, int inL, int inR) {
if(postL > postR) {
return NULL;
}
node* root = new node;
root->data = post[postR];
int k;
for(k=inL; k<=inR; k++) {
if(post[postR]==in[k])
break;
}
int numLeft = k - inL;
root->lchild = create(postL, postL+numLeft-1, inL, k-1);
root->rchild = create(postL+numLeft, postR-1, k+1, inR);
return root;
}
9.2 二叉树
最新推荐文章于 2023-01-06 17:20:07 发布