简体   繁体   English

创建二叉树而不是二叉搜索树

[英]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,则树应该看起来像

   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)? 对于第一个节点,一切正常。.但是,对于下一个节点(如果我要将4,5作为子级插入2,然后将6,7作为子级插入3),我应该如何在父级(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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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