二叉树的建立
void PreCreateBiTree(BiTree &T) {
char ch;
scanf("%c", &ch);
if (ch == '#') {
T = nullptr;
} else {
T = (BiTree) malloc(sizeof(BiNode));
T->data = ch;
PreCreateBiTree(T->lchild);
PreCreateBiTree(T->rchild);
}
}
void CreateFull(BiTree &root, int numbers[], int len, int i) {
if (i <= len) {
root->data = numbers[i - 1];
if (2 * i <= len && numbers[2 * i - 1] != 0) {
root->lchild = CreatNode();
CreateFull(root->lchild, numbers, len, 2 * i);
}
if (2 * i + 1 <= len && numbers[2 * i] != 0) {
root->rchild = CreatNode();
CreateFull(root->rchild, numbers, len, 2 * i + 1);
}
}
}
//in and pre , in and post
//this two can make a tree
//这些都是对中序遍历进行分割,先序后序确定中间的位置
链性保存为连续保存
int b[30] = {0};//全部赋值为0,之后建立的时候要找到最后一个不是0的位置为n,再将其丢进层序建树中
changeTo(T, 1, b);
void changeTo(BiTree T, int i, int *cloo) {
if (!T) {
return;
} else {
cloo[i - 1] = T->data;
changeTo(T->lchild, 2 * i, cloo);
changeTo(T->rchild, 2 * i + 1, cloo);
}
}
二叉树的遍历
void PreOrder(BiTree T){
if(T != null){
visit(T);
PreOrder(T->lchild);
PreOrder(T->rchild);
}
}
void PreOrder(BiTree T){
InitStack(S);
BiTree p = T;
while(p||!IsEmpty(S)){
if(p){
visit(p);
Push(S,p);
p = p->lchild;
}else{
Pop(S,p);
p = p->rchild;
}
}
}
void InOrder(BiTree T){
if(T != null){
InOrder(T->lchild);
visit(T);
InOrder(T->rchild);
}
}
void PreOrder(BiTree T){
InitStack(S);
BiTree p = T;
while(p || !Empty(S)){
if(p){
Push(S,p);
p = p->lchild;
}else{
Pop(S,p);
visit(p);
p = p->rchild;
}
}
}
void PostOrder(BiTree T){
if(T != null){
PostOrder(T->lchild);
PostOrder(T->rchild);
visit(T);
}
}
void PostOrder(BiTree T){
InitStack(S);
p = T;
r = Null;
while(p||!IsEmpty){
if(p){
push(S,p);
p = p->lchild;
}else{
GetTop(S,p);
if(p->rchild && p->rchild != r)
p = p->rchild;
else{
pop(S,p);
visit(p->data);
r = p;
p = Null;
}
}
}
}
void LevelOrder(BiTree T){
InitQueue(Q);
BiTree p;
EnQueue(Q,T);
while(!Empty(Q)){
DeQueue(Q,p);
visit(p);
if (p->lchild){
EnQueue(Q,p->lchild);
}
if (p->rchild){
EnQueue(Q,p->rchild);
}
}
}
#depth
int Btdepth(BiTree T){
if(T==Null)
return 0;
ldept = Btdepth(T->lchild);
rdept = Btdepth(T->rchild);
if(ldept > rdept){
return ldept+1;
}else{
return rdept+1;
}
}
非递归没有写