在C中创建一个右倾斜的二叉树

时间:2014-09-02 15:50:10

标签: c binary-tree treenode adjustment

在此程序中,用户应该能够从输入整数序列创建任意二叉树,并且应该能够在balancedleft_onlyright_only之间进行选择。我为平衡二叉树创建了它,但现在我无法将其调整为仅右侧而只留下树。

struct node {
    int data;
    struct node* left;
    struct node* right;
};

struct tree {
    struct node* root;
};

int init(struct tree* t) {
    t->root = 0;
    return 1;
}

struct node* makeNode(int d) {
    struct node* ptr;
    ptr = (struct node*)malloc(sizeof(struct node));
    ptr->data = d;
    ptr->left = ptr->right = 0;
    return ptr;
}

// sorting the binary tree
struct node* insertrchild(struct node* n, int d) {
    return (n->right = makeNode(d));
}
struct node* insertlchild(struct node* n, int d) {
    return (n->left = makeNode(d));
}

struct node* insertbst(struct node** ptr, int d) {
    if (*ptr == 0)
        return (*ptr = makeNode(d));
    if (d > (*ptr)->data)
        insertbst(&(*ptr)->right, d);
    else
        insertbst(&(*ptr)->left, d);
}

void inorder(struct node* ptr) // Print Tree
{ // Perform Inorder Traversal of tree
    if (ptr == 0) {
        return;
    }
    inorder(ptr->left);
    printf(" %d ", ptr->data);
    inorder(ptr->right);
}

void preorder(struct node* ptr) {
    if (ptr == 0)
        return;
    printf("%i\t", ptr->data);
    preorder(ptr->left);
    preorder(ptr->right);
}

void postorder(struct node* ptr) {
    if (ptr == 0)
        return;
    postorder(ptr->left);
    postorder(ptr->right);
    printf("%i\t", ptr->data);
}

如何调整此代码?

1 个答案:

答案 0 :(得分:2)

二叉树,因为我一直都知道结构(也许,我完全错了),有一个订单。每个新元素(小于当前节点)向左移动。每个节点,大于当前节点向右移动。反之亦然。
在您的示例中,您具有将新节点放在左侧或右侧的功能。所以有什么问题?呼叫右插入,你将有正确的藤蔓,呼叫左插入,你将离开藤蔓,但没有任何意义(恕我直言)。
通常,平衡二叉树是插入良好分布值(因此,混洗)的结果。例如,插入10,7,9,12,6

enter image description here

如果您插入有序套装,您将制作葡萄藤。例如3,4,6,7,9,10,11,12,14

enter image description here

此外,您可以制作类似

的内容

enter image description here

如果插入10,50,15,45,20,35,30,34,31(有序和无序组,一个接一个)。就像葡萄树一样,它有O(n)用于搜索。