和二叉树层次遍历(C语言)有关,想问一下这样写为什么不对?我应该怎么改才行呢?如果可以的话,能具体讲讲吗?(请就用我这种方法)谢谢了(^ω^)
函数接口定义:
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );
BinTree结构定义:
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
裁判测试程序样例:
#include
#include
typedef char ElementType;
typedef struct TNode *Position;
typedef Position BinTree;
struct TNode{
ElementType Data;
BinTree Left;
BinTree Right;
};
BinTree CreatBinTree(); /* 实现细节忽略 */
void InorderTraversal( BinTree BT );
void PreorderTraversal( BinTree BT );
void PostorderTraversal( BinTree BT );
void LevelorderTraversal( BinTree BT );
int main()
{
BinTree BT = CreatBinTree();
printf("Inorder:"); InorderTraversal(BT); printf("\n");
printf("Preorder:"); PreorderTraversal(BT); printf("\n");
printf("Postorder:"); PostorderTraversal(BT); printf("\n");
printf("Levelorder:"); LevelorderTraversal(BT); printf("\n");
return 0;
}
/* 你的代码将被嵌在这里 */
我的代码:
#define Max 1000
typedef enum {false,true} bool;
typedef struct Node *pr;
struct Node{
char *Data;
int f;
int r;
int Max;
};
typedef pr Queue;
void InorderTraversal( BinTree BT ){
if(BT){
PreorderTraversal(BT->Left);
printf("%d",BT->Data);
PreorderTraversal(BT->Right);
}
}
void PreorderTraversal( BinTree BT ){
if(BT){
printf("%d",BT->Data);
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
}
}
void PostorderTraversal( BinTree BT ){
if(BT){
PreorderTraversal(BT->Left);
PreorderTraversal(BT->Right);
printf("%d",BT->Data);
}
}
Queue CreatQueue(int Max){
Queue Q=(Queue)malloc(sizeof(struct QNode));
Q->Data=(char *)malloc(Max*sizeof(char));
Q->f=Q->r=0;
Q->Max=Max;
return Q;
}
bool AddQ(Queue Q,int X){
if((Q->r+1)%Q->Max==Q->f)
return false;
else{
Q->r=(Q->r+1)%Q->Max;
Q->Data[Q->r]=X;
return true;
}
}
bool DeleteQ(Queue Q){
if(Q->r == Q->f){
//printf("invalid\n");
return false;
}else{
Q->f=(Q->f+1)%Q->Max;
return true;
}
}
void LevelorderTraversal( BinTree BT ){
Queue Q=CreatQueue();
BinTree T;
AddQ(Q,BT);
while(Q){
T=define(Q);
printf("%d",T->Data);
if(T->Left){
AddQ(Q,T->Left);
}
if(T->Right){
AddQ(Q,T->Right);
}
}
}
T=define(Q);
define???
# 创建一个二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
# 进行层次遍历
result = level_order_traversal(root)
print(result) # 输出:[[1], [2, 4], [3, 5]]