顺序存储
只有完全二叉树(满二叉树,大小堆)才能使用顺序存储,因为他的存储形式固定
可以用数组实现,例如从1-99的完全二叉树:
#include <bits/stdc++.h>
using namespace std;
int main()
{
int tree[99] = {};
for(int i = 1;i < 9;++i) tree[i] = i;
}
父节点和子节点的下标有如下关系:
下标从0开始时:
dad * 2 +1 = 左孩子
dad * 2 + 2 = 右孩子
下标从1开始时:
dad * 2 = 左孩子
dad * 2 + 1 = 右孩子
链式存储
最常见以一种存储方式
下面是用最易懂的方式实现最简单的二叉树
#include <bits/stdc++.h>
using namespace std;
typedef struct list_point
{
int _data;
struct list_point *_left,*_right;
}*point;
int main()
{
point head = (point)malloc(sizeof(list_point));
head->_left = nullptr;
head->_right = nullptr;
head->_data = 1;
point left = (point)malloc(sizeof(list_point));
left->_left = nullptr;
left->_right = nullptr;
left->_data = 2;
point right = (point)malloc(sizeof(list_point));
right->_left = nullptr;
right->_right = nullptr;
right->_data = 3;
head->_left = left;
head->_right = right;
return 0;
}