creating binary tree not binary search tree

大城市里の小女人 提交于 2019-12-25 06:46:25

问题


I want to create a binary tree which fills from left to right. i.e. 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
}
}

回答1:


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;
}


来源:https://stackoverflow.com/questions/23668389/creating-binary-tree-not-binary-search-tree

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!