1.顺序存储
1.1二叉树
struct Tree {
int* node; // 存储二叉树节点的数组
int num; // 数组中实际占用的元素个数
};
(1)翻转
// 翻转二叉树
void invertTree(Tree& tree, int index) {
if (index >= tree.num || tree.node[index] == -1) {
return; // 空节点或超出范围
}
// 交换左右孩子
int leftIndex = 2 * index + 1;
int rightIndex = 2 * index + 2;
// 递归翻转左右子树
invertTree(tree, leftIndex);
invertTree(tree, rightIndex);
// 交换左右孩子
if (leftIndex < tree.num && rightIndex < tree.num) {
swap(tree.node[leftIndex], tree.node[rightIndex]);
}
}
(2)深度
// 计算二叉树的深度
int treeDepth(const Tree& tree, int index) {
if (index >= tree.num || tree.node[index] == -1) {
return 0; // 空节点或超出范围
}
// 递归计算左右子树的深度
int leftDepth = treeDepth(tree, 2 * index + 1);
int rightDepth = treeDepth(tree, 2 * index + 2);
// 返回左右子树深度的最大值加1(当前节点)
return max(leftDepth, rightDepth) + 1;
}