我對二叉搜索樹有兩個問題 - 一個關於我正在編寫的代碼,另一個關於理論。首先,我在下面寫的代碼工作正常,除了當我試圖顯示BST實際上是空的情況;當我希望打印出錯誤信息時,它會給我一個分段錯誤。我覺得我可能在某個時候弄混了我的指針,所以這給我帶來了錯誤。這裏是我的代碼:關於二叉搜索樹的兩個問題
#include <stdio.h>
#include <stdlib.h>
struct Node {
char *word;
struct Node *left;
struct Node *right;
};
/* Function that creates a new node as a leaf; that is, its */
/* left and right children are NULL. */
/* Require: node -> word != NULL */
struct Node * createNode (char *word) {
struct Node *item = malloc(sizeof(struct Node));
item -> word = word;
item -> left = NULL;
item -> right = NULL;
return item;
}
/* Recursive function that inserts a node into proper position by */
/* searching through tree. */
struct Node * insertNode (struct Node *root, char *word) {
// If tree is empty, node becomes root
if(root == NULL)
return createNode(word);
else {
if(strcmp(word, root -> word) < 0) {
root -> left = insertNode(root -> left, word);
return root;
} else if(strcmp(word, root -> word) > 0) {
root -> right = insertNode(root -> right, word);
return root;
} else if(strcmp(word, root -> word) == 0)
printf("Word is already present in the tree.");
}
}
/* Function to display Binary Search Tree via inorder traversal. */
/* -- prints entire left subtree, then root, then right subtree */
void display (struct Node *root) {
if(root -> word == NULL)
printf("Tree is empty.");
if(root -> left != NULL)
display(root -> left);
printf("%s\n", root -> word);
if(root -> right != NULL)
display(root -> right);
}
void main() {
struct Node root;
struct Node *rootP = &root;
root = createNode("
}
第二個問題涉及填充二叉樹。我想用一個小字典,當然會按字母順序排列。如果我將這些單詞以「Aardvark」作爲開頭,將這些單詞輸入到二叉樹中,那麼樹會不會因爲所有後續單詞在第一個按字母順序排列後出現令人難以置信的偏斜,從而始終是正確的孩子?我恐怕最終會得到一棵令人難以置信的不平衡的樹!當我填充它時,有什麼方法可以用來隨機播放樹嗎?
感謝您花時間閱讀本文!
謝謝你的答案!我現在要讀的是:) – 2011-04-06 06:14:13