我的程序的最後一部分存在問題。我應該使用堆棧將BST更改爲數組。當我嘗試執行該程序的這一部分時,出現段錯誤。我將發佈一些我的代碼,讓你們知道我想做什麼,然後發佈我應該使用這個函數的輸出。我在這裏先向您的幫助表示感謝。使用堆棧和push和pop函數將BST轉換爲數組
typedef struct TreeNode_ {
char name[MAX_NAME_LEN];
struct TreeNode_ *left;
struct TreeNode_ *right;
}TreeNode;
typedef struct StackNode_ {
TreeNode *t;
struct StackNode_ *next;
}StackNode;
char** flatten_tree(TreeNode* node, int *len_strings);
void push_node(StackNode** top, TreeNode* t);
TreeNode* pop_node(StackNode** top);
int size(TreeNode *node);
int main (int argc, char *argv[]) {
/*
* Check command line parameters
* */
if (argc < 2) {
printf("%s is missing parameters to run properly\n", argv[0]);
return 1;
}
TreeNode* root = NULL;
root = read_from_file(argv[1]);
char buffer[MAX_NAME_LEN];
char buffer2[MAX_NAME_LEN];
display_tree(root,START_DEPTH);
printf("Trimming the database from %s to %s\n\n", buffer, buffer2);
root = trim_tree(root,buffer,buffer2);
display_tree(root,START_DEPTH);
int size = 0;
char** strings = flatten_tree(root,&size);
int i = 0;
printf("\nFlattened databse is:\n");
for (i = 0; i < size; ++i) {
printf("%s\n", strings[i]);
free(strings[i]);
}
free(strings);
}
}
int size(TreeNode* node) {
if(node==NULL){
return 0;
}
else{
return(size(node->left) + 1 + size(node->right));
}}
char** flatten_tree(TreeNode* node, int *len_strings) {
*len_strings = size(node);
char *strings = malloc(sizeof(len_strings));
TreeNode* current = node;
StackNode* s = NULL;
int done = 0;
int i = 0;
*strings = strings[i];
while(!done){
if(current != NULL){
push_node(&s, current);
current = current->left;
}
else{
if(s){
current = pop_node(&s);
current = current->right;
strings[i++];
}
else
done = 1;
}
}
}
void push_node(StackNode** top, TreeNode* t) {
StackNode *newPtr = NULL;
if(newPtr != NULL)
{
newPtr->t = t;
newPtr->next = *top;
*top = newPtr;
}
}
TreeNode* pop_node(StackNode** top_ref) {
StackNode *top = *top_ref;
if(top){
StackNode *temp = top->next;
free(top_ref);
*top_ref = top;
}
}
該程序的輸出應該是這樣的:
-
bob
-
erik
-
james
-
matt
-
nick
-
sachin
-
sue
-
Flattened database is:
bob
erik
james
matt
nick
sachin
sue
我的輸出是這樣的:
-
bob
-
erik
-
james
-
matt
-
nick
-
sachin
-
sue
-
Flattened database is:
segmentation fault
應該看起來像這樣......它實際上是什麼樣子......? :) –
哦,它顯示樹,但它在平坦的數據庫部分seg故障,以便不顯示。我遺漏了一堆函數,雖然這會顯示bst –
'flatten_tree'沒有'return'語句 –