typedef struct BiTNode{
int data;//数据域
struct BiTNode *lchild,*rchild;//左右孩子
}BiTNode,*BiTree;
//前序遍历非递归
void preOrderTraversal(BiTree T) {
if (T == NULL) {
return;
}
Stack S; // 创建一个栈
initStack(&S); // 初始化栈
push(&S, T); // 将根节点压入栈
while (!isEmpty(&S)) {
BiTree node = pop(&S); // 弹出栈顶节点
printf("%d ", node->data); // 访问节点数据
if (node->rchild != NULL) {
push(&S, node->rchild); // 右子树不为空则压入栈
}
if (node->lchild != NULL) {
push(&S, node->lchild); // 左子树不为空则压入栈
}
}
}
//中序遍历转非递归
void inOrderTraversal(BiTree T) {
if (T == NULL) {
return;
}
Stack S; // 创建一个栈
initStack(&S); // 初始化栈
BiTree node = T; // 从根节点开始
while (node != NULL || !isEmpty(&S)) {
while (node != NULL) {
push(&S, node); // 将当前节点压入栈
node = node->lchild; // 移动到左子树
}
node = pop(&S); // 弹出栈顶节点
printf("%d ", node->data); // 访问节点数据
node = node->rchild; // 移动到右子树
}
}
//后序遍历转非递归
void postOrderTraversal(BiTree T) {
if (T == NULL) {
return;
}
Stack S; // 创建一个栈
initStack(&S); // 初始化栈
BiTree node = T; // 从根节点开始
BiTree lastVisit = NULL; // 上次访问的节点
while (node != NULL || !isEmpty(&S)) {
while (node != NULL) {
push(&S, node); // 将当前节点压入栈
node = node->lchild; // 移动到左子树
}
node = getTop(&S); // 获取栈顶节点但不弹出
if (node->rchild == NULL || node->rchild == lastVisit) {
printf("%d ", node->data); // 访问节点数据
pop(&S); // 弹出栈顶节点
lastVisit = node; // 更新上次访问的节点
node = NULL; // 置空当前节点,下次循环将弹出栈顶节点
} else {
node = node->rchild; // 移动到右子树
}
}
}
//求树高
int getTreeHeight(BiTree T) {
if (T == NULL) {
return 0;
}
Queue queue; // 创建一个队列
initQueue(&queue); // 初始化队列
int level = 0; // 树的层数
int width = 1; // 当前层的节点数
BiTree node = T; // 从根节点开始
enqueue(&queue, node); // 将根节点入队
while (!isEmpty(&queue)) {
node = dequeue(&queue); // 出队一个节点
width--; // 当前层节点数减一
if (node->lchild != NULL) {
enqueue(&queue, node->lchild); // 左子树不为空则入队
}
if (node->rchild != NULL) {
enqueue(&queue, node->rchild); // 右子树不为空则入队
}
if (width == 0) {
level++; // 当前层遍历完,层数加一
width = getSize(&queue); // 更新下一层节点数
}
}
return level; // 返回树的高度
}
递归转非递归的相关算法
最新推荐文章于 2024-07-24 19:35:30 发布