【发布时间】:2018-06-12 13:53:54
【问题描述】:
我对 C 语言相当陌生。我开始学习数据结构,并且对链表、堆栈和队列很熟悉。现在我正在实施 BST,它们似乎很复杂。在这里,我尝试为 Level Order Transversal 编写代码,但没有得到所需的输出。
请帮我修复它。
它没有显示任何错误。在运行程序时,我得到无限的“G”作为我的输出。我希望以某种顺序打印所有字符(我在主函数中输入的)。
#include <stdio.h>
#include <stdlib.h>
struct Node
{
char data;
struct Node* right;
struct Node* left;
};
void enq(struct Node* temproot);
struct Node* deq();
struct Node* Insert(struct Node* ,char x);
struct Node* newNode (char data);
void LevelOrder(struct Node* root);
struct Node* front = NULL;
struct Node* rear = NULL;
int main()
{
struct Node* root;
root = NULL;
root = Insert(root,'F');
root = Insert(root,'B');
root = Insert(root,'C');
root = Insert(root,'D');
root = Insert(root,'E');
root = Insert(root,'G');
root = Insert(root,'A');
root = Insert(root,'H');
root = Insert(root,'I');
LevelOrder(root);
return 0;
}
struct Node* Insert(struct Node* root,char x)
{
if (root == NULL)
{
root = newNode(x);
}
else if (x <= root->data)
{
root->left = Insert(root->left, x);
}
else
{
root->right = Insert(root->right,x);
}
return root;
}
struct Node* newNode(char x)
{
struct Node* temp1 = (struct Node*)malloc(sizeof(struct Node));
temp1->data = x;
temp1->right = NULL;
temp1->left = NULL;
return temp1;
}
void enq(struct Node* temproot)
{
struct Node* temp = (struct Node*)malloc(sizeof(struct Node));
temp->data = temproot->data;
temp->right = temp->left= NULL;
if(front == NULL && rear == NULL)
{
front = rear = temp;
return;
}
rear->right = temp;
rear = temp;
}
struct Node* deq()
{
struct Node* temp = front;
if (front == NULL)
{
printf("The queue is empty!");
}
else if (rear == front)
{
front = rear = NULL;
}
else
{
front = front->right;
}
return temp;
}
void LevelOrder(struct Node* root)
{
struct Node* temproot = root;
while(temproot != NULL)
{
printf("%c ", temproot->data);
if(temproot->left != NULL)
{enq(temproot->left);
}
if (temproot->right !=NULL)
{enq(temproot->right);
}
temproot = deq();
}
}
【问题讨论】:
-
你试过使用你的调试器吗?
-
Quote: “我没有得到所需的输出” 嗯,好吧……那么你得到了什么输出?你期待什么?
-
它没有显示错误。在运行程序时,我得到无限的“G”作为我的输出。我希望以某种顺序打印所有字符(我在 main 函数中输入的)。
-
@RohitBajaj 使用该信息编辑您的问题。还有预期的输出
-
您将右大括号
}比左大括号{缩进一级的系统非常不寻常(但非常一致)——我以前从未见过。我不认为它有助于可读性。肯定不是正统的indentation style。它最接近 Allman(我的首选风格),但它的右大括号与开大括号的缩进水平相同。我强烈推荐 Allman 或 1TBS 风格。
标签: c data-structures binary-tree