二叉树
二叉树的存储结构与基本操作
- 用二叉链表来存储
#include <iostream>
using namespace std;
struct node
{
int data;
node *lchild;
node *rchild;
};
//新建节点
node *create(int v)
{
node *Node = new node; //申请一个node型变量的地址空间
Node->data = v;
Node->lchild = NULL; //必须加这句话
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); //递归式
}
//二叉树节点的插入
void insert(node *&root, int x)
{
if (root == NULL) //递归边界
{
root = create(x);
return;
}
if ("需要在左子树插入数据")
{
insert(root->lchild, x); //递归式
}
else
{
insert(root->rchild, x);
}
}
//二叉树的创建
node *build(int data[], int n)
{
node *root = NULL; //新建空根节点root
for (int i = 0; i < n; i++)
{
insert(root, data[i]);
}
return root;
}
二叉树的遍历
先序遍历
- 根节点-----左子树----右子树
void preorder(node *root)
{
if (root == NULL) //到达空树,递归边界
{
return;
}
cout<<root->data<<endl;
preorder(root->lchild);
preorder(root->rchild);
}
中序遍历
- 左子树----根节点----右子树
void inorder(node *root)
{
if (root == NULL) //到达空树,递归边界
{
return;
}
inorder(root->lchild);
cout << root->data << endl;
inorder(root->rchild);
}
后序遍历
- 左子树----右子树----根节点
void postorder(node *root)
{
if (root == NULL) //到达空树,递归边界
{
return;
}
postorder(root->lchild);
postorder(root->rchild);
cout << root->data << endl;
}
层次遍历
void LayerOrder(node *root)
{
queue<node*> q; //node*类型,因为push进去的知识原元素的一个副本
q.push(root);
while(!q.empty()){
node* top = q.front();
cout<<top->data<<endl;
if(top->lchild){
q.push(top->lchild);
}
if(top->rchild){
q.push(top->rchild);
}
}
}
二叉树的重建
//给定中序和先序序列创建二叉树,返回根节点的地址
node *create(int preL, int preR, int inL, int inR)
{
if (preL > preR)
{
return NULL; //先序长度小于等于0,直接返回
}
node *root = new node; //创建一个新的节点,用来存储当前二叉树的根节点
root->data = pre[preL];
int k = -1;
for (int i = inL; i <= inR; i++)
{
if (in[i] == pre[preL])
{
k = i;
break;
}
}
int numLeft = k - inL;
root->lchild = create(preL+1,preL+numLeft,inL,k-1);
root->rchild = create(preL+numLeft+1,preR,k+1,inR);
return root;
}