完全二叉树插入新结点

在一个完全二叉树中插入新的节点,注意这里的完全二叉树并非二叉搜索树,因此我们只需要定位最后一个结点就可以了,不需要满足二叉搜索树的条件。

一个最简单的想法就是BFS,如果不是満二叉树,找到第一个有一个子树为空的节点即可。否则,则需要找到最下一层的最左结点。

另外一个想法是利用完全二叉树的性质,首先判断左子树的最右结点与右子树的最右结点高度,如果相等,只需要插入到左子树即可,否则插入右子树。

它的递归程序如下:

Node* insert(Node* root,Node*newnode){
    if(!root||!newnode)return NULL;
    if(!root->l){
        root->l=newnode;
        return root;
    }
    else if(!root->r){
        root->r=newnode;
        return root;
    }
    int lrh=0;
    int rrh=0;
    Node *pNode=root->l;
    while(pNode){
        lrh++;
        pNode=pNode->r;
    }
    pNode=root->r;
    while(pNode){
        rrh++;
        pNode=pNode->r;
    }
    if(lrh!=rrh){
        return insert(root->r,newnode);
    }
    else
        return insert(root->l,newnode);
}


  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
在C语言,可以通过链表的方式来实现非二叉树插入结点操作。以下是一个简单的例子: ```c #include <stdio.h> #include <stdlib.h> // 定义树的结点类型 typedef struct TreeNode { int data; // 结点的数据 struct TreeNode *firstChild; // 第一个孩子结点 struct TreeNode *nextSibling; // 兄弟结点 } TreeNode; // 插入结点 void insertNode(TreeNode *parent, TreeNode *node) { if (parent == NULL) { return; } if (parent->firstChild == NULL) { parent->firstChild = node; } else { TreeNode *child = parent->firstChild; while (child->nextSibling != NULL) { child = child->nextSibling; } child->nextSibling = node; } } int main() { // 创建根结点 TreeNode *root = (TreeNode*)malloc(sizeof(TreeNode)); root->data = 1; root->firstChild = NULL; root->nextSibling = NULL; // 创建结点2、3、4 TreeNode *node2 = (TreeNode*)malloc(sizeof(TreeNode)); node2->data = 2; node2->firstChild = NULL; node2->nextSibling = NULL; TreeNode *node3 = (TreeNode*)malloc(sizeof(TreeNode)); node3->data = 3; node3->firstChild = NULL; node3->nextSibling = NULL; TreeNode *node4 = (TreeNode*)malloc(sizeof(TreeNode)); node4->data = 4; node4->firstChild = NULL; node4->nextSibling = NULL; // 插入结点2、3、4 insertNode(root, node2); insertNode(root, node3); insertNode(node2, node4); // 输出树的结点 printf("Tree: root(%d)->", root->data); TreeNode *child = root->firstChild; while (child != NULL) { printf("(%d)->", child->data); child = child->nextSibling; } printf("NULL\n"); return 0; } ``` 在上面的例子插入结点的操作通过遍历找到最后一个兄弟结点,并将结点插入到其后面。注意,如果某个结点没有孩子结点,则其 `firstChild` 指针应该被设置为 `NULL`。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值