简体   繁体   中英

creating binary tree not binary search tree

I want to create a binary tree which fills from left to right. ie if 1,2,3 are to be inserted then the tree should look like

   1
 /   \
2     3

I wrote an insert function, to insert the nodes in the tree. For the first node everything works okay..But, for the next node's (if I want to insert 4,5 as children to 2 and later 6,7 as children to 3) how should I switch between the parents (2,3)?

Here's my insert function

struct node * Insert(struct node * node, int data) {
if(node == NULL)
    return (newNode(data));
else {
    if(!node->left)
        node->left = Insert(node->left,data);
    if(!node->right)
        node->right = Insert(node->right,data);
    //can't figure out the condition when they both fail
}
}
struct node **InsertPoint(struct node **node, int *level){
    if(*node == NULL)
        return node;

    int left_level, right_level;
    struct node **left_node, **right_node;
    left_level = right_level = *level + 1;
    left_node  = InsertPoint(&(*node)->left,  &left_level );
    right_node = InsertPoint(&(*node)->right, &right_level);
    if(left_level <= right_level){
        *level = left_level;
        return left_node;
    } else {
        *level = right_level;
        return right_node;
    }
}

struct node *Insert(struct node *node, int data) {
    struct node **np;
    int level = 0;
    np = InsertPoint(&node, &level);
    *np = newNode(data);
    return node;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM