王道C语言C++版树的顺序存储结构代码总结--树1

二叉树的顺序存储结构

#define MAX_TREE_SIZE 100
typedef int SqBiTree[MAX_TREE_SIZE];
SqBiTree bt;

在顺序结构中寻找i和j的最近共同祖先

#include<cstdio>

//二叉树的顺序存储结构
#define MAX_TREE_SIZE 100
typedef int SqBiTree[MAX_TREE_SIZE];
SqBiTree bt;

//在顺序结构中寻找i和j的最近共同祖先
void Comm_Ancester(SqBiTree bt, int i, int j){
    int a = i, b = j;
    if(bt[i] == 0){
        printf("编号为%d的结点不存在!\n", i);
        return;
    }
    if(bt[j] == 0){
        printf("编号为%d的结点不存在!\n", j);
        return;
    }

    while(i != j){//谁大谁往上跳一层再比,直到相等
        if(i > j)
            i /= 2;
        else
            j /= 2;
    }
    printf("编号为%d的结点和编号为%d的结点的最近公共祖先的结点编号为%d,其值为%d\n", a, b, i, bt[i]);
}

int main()
{
    int bt[] = {-1, 1, 2,3, 4,5,6,7, 8,0,10,0,0,0,0,0, 0,0,0,0};//层次序列
    /*
                 1
             /       \
          2            3
        /   \        /   \
       4     5      6     7
     /  \  /   \   / \   / \
    8   0 10   0  0  0  0  0
   / \   / \
  0  0  0  0
    */
    //在上述顺序存储结构中寻找编号为i和j结点的最近共同祖先结点的编号和值
    Comm_Ancester(bt, 2, 3);
    Comm_Ancester(bt, 4, 5);
    Comm_Ancester(bt, 4, 6);
    Comm_Ancester(bt, 8, 10);
    /*
    编号为2的结点和编号为3的结点的最近公共祖先的结点编号为1,其值为1
    编号为4的结点和编号为5的结点的最近公共祖先的结点编号为2,其值为2
    编号为4的结点和编号为6的结点的最近公共祖先的结点编号为1,其值为1
    编号为8的结点和编号为10的结点的最近公共祖先的结点编号为2,其值为2
    */

    return 0;
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
王道数据结构课后代码C语言完整版可以有很多种不同的代码示例,如下是一个实现链表的示例: ```c #include <stdio.h> #include <stdlib.h> typedef struct Node { int data; struct Node* next; } Node; Node* createNode(int data) { Node* newNode = (Node*)malloc(sizeof(Node)); newNode->data = data; newNode->next = NULL; return newNode; } void insert(Node** head, int data) { if (*head == NULL) { *head = createNode(data); return; } Node* curr = *head; while (curr->next != NULL) { curr = curr->next; } curr->next = createNode(data); } void display(Node* head) { Node* curr = head; while (curr != NULL) { printf("%d ", curr->data); curr = curr->next; } printf("\n"); } void delete(Node** head, int data) { if (*head == NULL) { return; } Node* curr = *head; Node* prev = NULL; // 如果要删除的元素是第一个节点 if (curr->data == data) { *head = curr->next; free(curr); return; } // 否则遍历链表找到要删除的元素 while (curr != NULL && curr->data != data) { prev = curr; curr = curr->next; } // 如果找到了要删除的元素 if (curr != NULL) { prev->next = curr->next; free(curr); } } int main() { Node* head = NULL; insert(&head, 1); insert(&head, 2); insert(&head, 3); insert(&head, 4); display(head); delete(&head, 2); display(head); return 0; } ``` 以上代码实现了一个简单的链表数据结构,在main函数中对链表进行了插入和删除操作,并打印出链表中的元素。这只是一个简单的示例,王道数据结构课本中还有很多其他的数据结构和算法代码可以一一学习和实现。

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值