栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

【LeetCode-中等】919. 完全二叉树插入器(C++实现)

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【LeetCode-中等】919. 完全二叉树插入器(C++实现)

文章目录
    • 题目链接
    • 实现思路
    • 实现代码(C++)

题目链接

919. 完全二叉树插入器

实现思路
  • CBTInserter 要求实现一个完全二叉树。

    根据完全二叉树的特性,可以用数组来辅助存储二叉树。

    使用层序遍历把各节点入数组。

  • insert():

    新建节点,插入数组后和父节点建立联系即可。

    (假设下标从 1 开始)在这个完全二叉树中,下标为 i 的节点的父节点的下标为 ⌊ i / 2 ⌋ lfloor{i/2} rfloor ⌊i/2⌋。即

    int size = this->tree.size() - 1;
    int parent = size / 2;
    if (size % 2 == 0) {
        this->tree[parent]->left = this->tree.back();
    } else {
        this->tree[parent]->right = this->tree.back();
    }
    
  • get_root()

    如果当前数组大小<0,直接返回 nullptr;否则,返回下标为 1 的节点。

实现代码(C++)
class CBTInserter {
public:
    vector tree;
    CBTInserter(TreeNode* root) {
        this->tree.push_back(nullptr); // 从下标 1 开始存数据

        queue q;
        q.push(root);
        TreeNode* temp = root;
        while (!q.empty()) {
            temp = q.front();
            q.pop();
            this->tree.push_back(temp);
            if (temp->left) {
                q.push(temp->left);
            }
            if (temp->right) {
                q.push(temp->right);
            }
        }
    }
    
    int insert(int val) {
        TreeNode* node = new TreeNode(val);
        this->tree.push_back(node);

        int size = this->tree.size() - 1;
        int parent = size / 2;
        if (size % 2 == 0) {
            this->tree[parent]->left = this->tree.back();
        } else {
            this->tree[parent]->right = this->tree.back();
        }
        
        return this->tree[parent]->val;
    }
    
    TreeNode* get_root() {
        if (this->tree.size() == 1) {
            return nullptr;
        }
        return this->tree[1];
    }
};
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/1026160.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号