二叉树存入数组的代码
时间: 2024-05-11 08:13:02 浏览: 10
二叉树存入数组的方式通常称为顺序存储结构,具体实现方式如下:
首先,我们需要定义一个数组,用来存储二叉树节点的值,其中根节点的下标为1,其余节点的下标按照层序遍历的顺序从左到右递增。然后,我们可以通过下标计算每个节点的父节点、左子节点和右子节点在数组中的下标:
1. 父节点:对于一个下标为 i 的节点,其父节点的下标为 i/2。
2. 左子节点:对于一个下标为 i 的节点,其左子节点的下标为 2*i。
3. 右子节点:对于一个下标为 i 的节点,其右子节点的下标为 2*i+1。
最后,我们就可以使用数组来表示二叉树了。以下是一个简单的示例代码:
```c++
#include <iostream>
using namespace std;
const int MAXN = 100;
int tree[MAXN];
int main() {
// 假设有以下二叉树
// 1
// / \
// 2 3
// / \ / \
// 4 5 6 7
tree = 1;
tree = 2;
tree = 3;
tree = 4;
tree = 5;
tree = 6;
tree = 7;
// 计算父节点、左子节点和右子节点的下标
int parent = tree[2 / 2];
int leftChild = tree[2 * 2];
int rightChild = tree[2 * 2 + 1];
// 输出结果
cout << "Parent: " << parent << endl;
cout << "Left child: " << leftChild << endl;
cout << "Right child: " << rightChild << endl;
return 0;
}
```