在这个程序中,用户应该能够从输入整数序列创建任意二叉树,并且他们应该能够在 to balanced
、left_only
、之间进行选择right_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);
}
如何调整此代码?