408数据结构代码笔记(更新中)

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;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值