PTA 第六章 二叉树的遍历(中序遍历、前序遍历、后序遍历、层序遍历)、求深度、前序输出叶子结点

#include <bits/stdc++.h>

typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
    ElementType Data;
    BinTree Left;
    BinTree Right;
};

BinTree CreatBinTree(); /* 实现细节忽略 */
int GetHeight( BinTree BT );  //求深度的函数
void InorderTraversal( BinTree BT );//中序遍历函数
void PreorderTraversal( BinTree BT );//前序遍历函数
void PostorderTraversal( BinTree BT );//后序遍历函数
void LevelorderTraversal( BinTree BT );//层序遍历函数
void PreorderPrintLeaves( BinTree BT );//前序输出叶子结点

int main()
{
    BinTree BT = CreatBinTree();
    printf("%d\n", GetHeight(BT));
    printf("Inorder:");    InorderTraversal(BT);    printf("\n");
    printf("Preorder:");   PreorderTraversal(BT);   printf("\n");
    printf("Postorder:");  PostorderTraversal(BT);  printf("\n");
    printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
    printf("Leaf nodes are:");
    PreorderPrintLeaves(BT);
    printf("\n");

    return 0;
}
/* 你的代码将被嵌在这里 */
BinTree CreatBinTree()//前序
### C语言实现二叉树前序、中序和后序非递归遍历 #### 定义节点结构体 为了便于理解,先定义一个简单的二叉树节点结构体: ```c typedef struct TreeNode { char data; struct TreeNode *lChild, *rChild; } TreeNode; ``` #### 前序遍历非递归算法 前序遍历的顺序是根结点 -> 左子树 -> 右子树。可以利用栈来模拟这个过程。 ```c void preOrder(TreeNode *root) { if (root == NULL) return; TreeNode* stack[100]; int top = -1; TreeNode *p = root; while (p != NULL || top != -1) { while (p != NULL) { // 访问当前节点并压入左孩子到栈中 printf("%c ", p->data); stack[++top] = p; p = p->lChild; } if (top != -1) { p = stack[top--]; // 出栈并转向右孩子 p = p->rChild; } } } ``` #### 中序遍历非递归算法 中序遍历遵循左子树 -> 根结点 -> 右子树的原则。同样借助栈完成迭代操作。 ```c void inOrder(TreeNode *root) { TreeNode *stack[15], *p = root; int top = -1; while (p != NULL || top != -1) { if (p != NULL) { stack[++top] = p; // 将指针指向的节点地址存入数组作为“入栈” p = p->lChild; // 继续向左走直到最左边叶子节点 } else { p = stack[top--]; // “出栈”,恢复上一层次父节点位置 printf("%c ", p->data); // 输出数据域中的字符 p = p->rChild; // 转而处理右侧分支 } } } ``` #### 后序遍历非递归算法 对于后序遍历来说,其访问次序为左子树 -> 右子树 -> 根结点。这里采用两个栈的方法简化逻辑复杂度。 ```c void postOrder(TreeNode *root) { if (!root) return; TreeNode *stack1[100], *stack2[100]; int top1 = -1, top2 = -1; stack1[++top1] = root; while (top1 >= 0) { TreeNode *node = stack1[top1--]; stack2[++top2] = node; if (node->lChild) stack1[++top1] = node->lChild; if (node->rChild) stack1[++top1] = node->rChild; } while (top2 >= 0) { printf("%c ", stack2[top2--]->data); } } ``` 上述三种方法分别实现了二叉树前序、中序以及后序非递归遍历[^1][^2]。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值