C 在二叉树中插入节点
我试图在二叉树中插入1到7个数字。然后使用级别顺序遍历遍历树。 下面是我用来插入节点的函数:C 在二叉树中插入节点,c,algorithm,tree,queue,C,Algorithm,Tree,Queue,我试图在二叉树中插入1到7个数字。然后使用级别顺序遍历遍历树。 下面是我用来插入节点的函数: void InsertIntoBinaryTree(struct BinaryTree **root,int data) { struct BinaryTree *newNode,*tempNode; struct Queue queue; newNode = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
void InsertIntoBinaryTree(struct BinaryTree **root,int data)
{
struct BinaryTree *newNode,*tempNode;
struct Queue queue;
newNode = (struct BinaryTree *)malloc(sizeof(struct BinaryTree));
newNode -> data = data;
newNode -> left = newNode -> right = NULL;
if(!*root)
{
*root = newNode;
}
else
{
queue.rear = -1;
Enqueue(&queue,*root);
while(queue.front != -1)
{
tempNode = Dequeue(&queue);
if(tempNode -> left)
{
Enqueue(&queue,tempNode -> left);
}
else
{
tempNode -> left = newNode;
return;
}
if(tempNode -> right)
{
Enqueue(&queue,tempNode -> right);
}
else
{
tempNode -> right = newNode;
return;
}
}
}
}
根节点
节点已成功插入,但其他节点未成功插入。
插入root
节点后,我将把新节点分配到root
节点的左侧,然后分配到root
节点的右侧。新节点已分配,但一旦我遍历树,子节点就不会显示,子节点也不会排队到我用来跟踪已解析节点的临时队列中。
下面是用于级别顺序遍历的函数:
void LevelOrderTraversal(struct BinaryTree *root)
{
struct Queue q;
struct BinaryTree *tempNode;
if(root)
{
q.rear = -1;
Enqueue(&q,root);
while(q.front != -1)
{
tempNode = Dequeue(&q);
printf("address:%u and data:%d\t",tempNode,tempNode -> data);
if(tempNode -> left)
Enqueue(&q,tempNode -> left);
if(tempNode -> right)
Enqueue(&q,tempNode -> right);
}
}
printf("\n");
}
请帮我找出哪里出了问题。编辑:以下是排队和退队代码:
void Enqueue(struct Queue *q,struct BinaryTree *root)
{
// check queue is full.................
if((q -> rear + 1)% MAX==q->front)
printf("queue is full");
else{
if((q -> rear == -1)||(q->front==-1))
q -> rear = q -> front = 0;
else
q -> rear = (q -> rear + 1)% MAX;
q -> a[q -> rear] = root;
}
}
struct BinaryTree *Dequeue(struct Queue *q)
{
struct BinaryTree *temp;
if(q->front==-1)
return NULL;
else{
temp = q -> a[q -> front];
if(q -> front == q -> rear)
q -> front = q -> front = -1;
else
q -> front = (q -> front + 1)% MAX;
return temp;
}
}
所示代码插入并遍历树级别(宽度优先)。队列是否按预期工作?是的,队列工作正常。基本上,您的队列工作正常。在
Dequeue
中,您可能需要q->front=q->reast=-1代码>。在某些情况下,您可能会初始化q.rear=-1
,而未初始化的q.front
为0,这会导致队列认为它已满,尽管它不是。此外,您应该使用%p
打印指针的值,或者在打印时将其转换为(unsigned int)
。我能想到的另一个陷阱是,您没有将root初始化为NULL
。除此之外,您的代码应该可以工作。是的。谢谢,我知道了。我在main
方法中缺少q.front=-1
。