2
我想按鋸齒形順序打印樹。這是我的代碼,但它沒有運行。有人可以指出這個錯誤嗎? 我已經創建了兩個堆棧來做同樣的事情,當我的算法中有兩個是空的時候,我的算法終止,如果它們中的任何一個包含一些節點,那麼這些節點被打印出來並且它的子節點被推入另一個堆棧。這個過程繼續下去,直到兩個堆棧變空。之字形樹印刷
#include<stdio.h>
#define MAX_SIZE 100
struct TreeNode{
int value;
struct TreeNode *left;
struct TreeNode *right;
};
struct TreeNode stackA[MAX_SIZE];
struct TreeNode stackB[MAX_SIZE];
int topA = 0;
int topB = 0;
void push(struct TreeNode stack[], struct TreeNode *node, int *top){
if(*top > MAX_SIZE){
printf("stack is full\n");
}
else{
stack[*top] = *node;
*top = *top +1;
}
return;
}
struct TreeNode* pop(struct TreeNode stack[], int *top){
if(*top == 0){
printf("stack is empty\n");
return NULL;
}
else{
struct TreeNode *tmp = stack + *top;
*top = *top - 1;
return tmp;
}
}
int isEmpty(int *top){
if(*top == 0){
return 1;
}
return 0;
}
void printZigZag(struct TreeNode* root){
push(stackA, root,&topA);
printf("%d\n", topA);
while(!isEmpty(&topA) || !isEmpty(&topB)){
while(!isEmpty(&topA)){
struct TreeNode* temp = pop(stackA,&topA);
printf("%d", temp->value);
if(temp->left) push(stackB,temp->left,&topB);
if(temp->right) push(stackB,temp->right,&topB);
printf("%d %d",topA,topB);
return;
}
while(!isEmpty(&topB)){
struct TreeNode *temp = pop(stackB,&topB);
printf("%d", temp->value);
if(temp->right) push(stackA,temp->right,&topA);
if(temp->left) push(stackA,temp->left,&topB);
}
}
}
int main(){
struct TreeNode* root = (struct TreeNode *)malloc(sizeof(struct TreeNode));
root->value = 5;
root->left = NULL;
root->right = NULL;
struct TreeNode* first = (struct TreeNode *)malloc(sizeof(struct TreeNode));
first->value = 15;
first->left = NULL;
first->right = NULL;
root->left = first;
struct TreeNode* second = (struct TreeNode *)malloc(sizeof(struct TreeNode));
second->value = 235;
second->left = NULL;
second->right = NULL;
root->right = second;
struct TreeNode *third = (struct TreeNode *)malloc(sizeof(struct TreeNode));
third->value = 45;
third->left = NULL;
third->right = NULL;
first->left = third;
struct TreeNode *fourth = (struct TreeNode *)malloc(sizeof(struct TreeNode));
fourth->value = 55;
fourth->left = NULL;
fourth->right = NULL;
first->right = fourth;
printZigZag(root);
system("pause");
return 0;
}
一個問題是您不會刷新您打印的輸出,這意味着在程序完成之前您將看不到任何輸出。爲'printf'調用添加換行符,或爲'stdout'顯式調用'fflush'。 –
只是爲了將來的工作,如果你想看到樹作爲圖像,我會建議你使用Graphviz。使你的C程序輸出graphviz代碼到一個文件,並用它來獲取圖像。只是一個想法,也許你會感興趣... – Goaler444