前言
建立
前序遍历
中序遍历
后序遍历
层次遍历
求二叉树深度
求二叉树宽度
二叉树的建立与遍历
code
#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
typedef struct BTNode
{
char data;
struct BTNode *lchild, *rchild;
}BTNode;
void CreateTree(BTNode *& T)
{
char c;
cin >> c;
if (c == '0')
{
T = NULL;
}
else
{
T = (BTNode *)malloc(sizeof(BTNode));
T->data = c;
CreateTree(T->lchild);
CreateTree(T->rchild);
}
}
void preOrder(BTNode *T)
{
if (T)
{
printf("%c\n", T->data);
preOrder(T->lchild);
preOrder(T->rchild);
}
}
void inOrder(BTNode *T)
{
if (T)
{
inOrder(T->lchild);
printf("%c\n", T->data);
inOrder(T->rchild);
}
}
void postOrder(BTNode *T)
{
if (T)
{
postOrder(T->lchild);
postOrder(T->rchild);
printf("%c\n", T->data);
}
}
int main()
{
BTNode *T;
CreateTree(T);
preOrder(T);
printf("\n");
inOrder(T);
printf("\n");
postOrder(T);
printf("\n");
return 0;
}
层次遍历
//层次遍历
void level(BTNode *T)
{
int front, rear;
BTNode *que[MaxSize];
front = rear = 0;
BTNode *q;
if (T)
{
rear = (rear + 1) % MaxSize;
que[rear] = T;
while (front != rear)
{
front = (front + 1) % MaxSize;
q = que[front];
printf("%c", q->data);
if (q->lchild)
{
rear = (rear + 1) % MaxSize;
que[rear] = q->lchild;
}
if (q->rchild)
{
rear = (rear + 1) % MaxSize;
que[rear] = q->rchild;
}
}
}
}
求二叉树深度函数
int getDepth(BTNode *T)
{
int LD, RD;
if (T == NULL)
{
return 0;
}
else
{
LD = getDepth(T->lchild);
RD = getDepth(T->rchild);
return (LD > RD ? LD : RD) + 1;
}
}
求二叉树的宽度
typedef struct
{
BTNode *p;
int lno;
}St;
int maxNode(BTNode *b)
{
St que[MaxSize];
int front, rear;
int Lno, i, j, n, max;
front = rear = 0;
BTNode *q;
if (b)
{
++rear;
que[rear].p = b;
que[rear].lno = 1;
while (front != rear)
{
++front;
q = que[front].p;
Lno = que[front].lno;
if (q->lchild)
{
++rear;
que[rear].p = q->lchild;
que[rear].lno = Lno + 1;
}
if (q->rchild)
{
++rear;
que[rear].p = q->rchild;
que[rear].lno = Lno + 1;
}
}
printf("Lno: %d\n", Lno);
max = 0;
for (i = 1; i <= Lno; i++)
{
n = 0;
for (j = 0; j < rear; j++)
{
if (que[j].lno == i)
{
++n;
}
if (n > max)
{
max = n;
}
}
}
return max;
}
return 0;
}