数据结构之二叉树的数组表示

二叉树的数组表示

表示完美二叉树

若某节点的索引为i,则该节点的左子节点的索引为2i+1,右子节点的索引为2i+2

代码实现

  • 给定某节点,获取它的左右字节点,父节点
  • 获取前序遍历,中序遍历,后序遍历,层序遍历
c++ 复制代码
/* 数组表示下的二叉树类 */
class ArrayBinaryTree {
  public:
    /* 构造方法 */
    ArrayBinaryTree(vector<int> arr) {
        tree = arr;
    }

    /* 列表容量 */
    int size() {
        return tree.size();
    }

    /* 获取索引为 i 节点的值 */
    int val(int i) {
        // 若索引越界,则返回 INT_MAX ,代表空位
        if (i < 0 || i >= size())
            return INT_MAX;
        return tree[i];
    }

    /* 获取索引为 i 节点的左子节点的索引 */
    int left(int i) {
        return 2 * i + 1;
    }

    /* 获取索引为 i 节点的右子节点的索引 */
    int right(int i) {
        return 2 * i + 2;
    }

    /* 获取索引为 i 节点的父节点的索引 */
    int parent(int i) {
        return (i - 1) / 2;
    }

    /* 层序遍历 */
    vector<int> levelOrder() {
        vector<int> res;
        // 直接遍历数组
        for (int i = 0; i < size(); i++) {
            if (val(i) != INT_MAX)
                res.push_back(val(i));
        }
        return res;
    }

    /* 前序遍历 */
    vector<int> preOrder() {
        vector<int> res;
        dfs(0, "pre", res);
        return res;
    }

    /* 中序遍历 */
    vector<int> inOrder() {
        vector<int> res;
        dfs(0, "in", res);
        return res;
    }

    /* 后序遍历 */
    vector<int> postOrder() {
        vector<int> res;
        dfs(0, "post", res);
        return res;
    }

  private:
    vector<int> tree;

    /* 深度优先遍历 */
    void dfs(int i, string order, vector<int> &res) {
        // 若为空位,则返回
        if (val(i) == INT_MAX)
            return;
        // 前序遍历
        if (order == "pre")
            res.push_back(val(i));
        dfs(left(i), order, res);
        // 中序遍历
        if (order == "in")
            res.push_back(val(i));
        dfs(right(i), order, res);
        // 后序遍历
        if (order == "post")
            res.push_back(val(i));
    }
};
相关推荐
网安INF19 分钟前
Python核心数据结构与函数编程
数据结构·windows·python·网络安全
.格子衫.2 小时前
018数据结构之队列——算法备赛
数据结构·算法
浩泽学编程2 小时前
【源码深度 第1篇】LinkedList:双向链表的设计与实现
java·数据结构·后端·链表·jdk
怎么没有名字注册了啊3 小时前
求一个矩阵中的鞍点
数据结构·算法
仟千意3 小时前
数据结构:二叉树
数据结构·算法
代码欢乐豆6 小时前
编译原理机测客观题(7)优化和代码生成练习题
数据结构·算法·编译原理
祁同伟.7 小时前
【C++】二叉搜索树(图码详解)
开发语言·数据结构·c++·容器·stl
Joy T7 小时前
Solidity智能合约存储与数据结构精要
数据结构·区块链·密码学·智能合约·solidity·合约function
海绵宝宝的好伙伴8 小时前
【数据结构】哈希表的理论与实现
数据结构·哈希算法·散列表
Aqua Cheng.8 小时前
代码随想录第七天|哈希表part02--454.四数相加II、383. 赎金信、15. 三数之和、18. 四数之和
java·数据结构·算法·散列表