关于二叉搜索树的两个问题

时间:2011-04-06 06:04:42

标签: c

我有两个关于二元搜索树的问题 - 一个关于我正在编写的代码,另一个关于理论。首先,我在下面编写的代码工作正常,除非我尝试显示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”,那么树不会因为所有后续单词按字母顺序排在第一位后因此总是正确的孩子而难以置信地倾斜吗?我担心我最终会得到一棵非常失衡的树!当我填充它时,是否有一些方法可以用来改变树的周围?

感谢您抽出宝贵时间阅读本文!

3 个答案:

答案 0 :(得分:3)

display函数中,您首先需要在测试root == null之前测试是否root -> word == null。这应该可以解决seg故障。

关于理论问题:答案是肯定的,这棵树最终将会出现令人难以置信的倾斜。这就是balanced binary trees的全部内容。

答案 1 :(得分:1)

if(root -> word == NULL)
    printf("Tree is empty.");

你的问题就在这里。如果root本身为null会发生什么?在取消引用之前仔细检查指针。

是的,如果您按排序顺序(或相对排序)插入项目,您将得到一个倾斜的树。研究平衡二叉树中节点旋转的算法。

答案 2 :(得分:0)

关于你的第二个问题,其他人已经提到了平衡你的二叉树。但是,作为替代方案,如果已知您的输入已被排序,则更合适的是使用带二进制搜索的线性数组来查找感兴趣的项目,而不是二叉树。对排序数组进行二进制搜索与在平衡二叉树中搜索具有相同的时间复杂度。