给我C++代码 存储int 的二叉数数据
时间: 2023-12-24 07:05:36 浏览: 26
好的,以下是用 C++ 实现存储 int 类型数据的二叉树的数组表示方式的示例代码:
```c++
#include <iostream>
using namespace std;
const int MAXN = 100; // 定义数组的最大长度
int tree[MAXN]; // 定义存储二叉树的数组
// 中序遍历二叉树
void inorderTraversal(int index) {
if (index >= MAXN || tree[index] == 0) return; // 数组越界或节点为空时返回
inorderTraversal(2 * index); // 遍历左子树
cout << tree[index] << " "; // 输出节点值
inorderTraversal(2 * index + 1); // 遍历右子树
}
int main() {
// 初始化二叉树
tree[1] = 1;
tree[2] = 2;
tree[3] = 3;
tree[4] = 4;
tree[5] = 5;
tree[6] = 6;
tree[7] = 7;
cout << "中序遍历结果:";
inorderTraversal(1); // 从根节点开始遍历
cout << endl;
return 0;
}
```
运行结果:
```
中序遍历结果:4 2 5 1 6 3 7
```
其中,inorderTraversal() 函数用于中序遍历二叉树,从根节点开始遍历。程序中初始化了一个深度为 3 的二叉树,可以根据自己的需求进行修改。