A *complete* binary tree is a binary tree in which every level, except possibly the last, is completely filled, and all nodes are as far left as possible.

Write a data structure CBTInserter that is initialized with a complete binary tree and supports the following operations:

  • CBTInserter(TreeNode root) initializes the data structure on a given tree with head node root;
  • CBTInserter.insert(int v) will insert a TreeNode into the tree with value node.val = v so that the tree remains complete, and returns the value of the parent of the inserted TreeNode;
  • CBTInserter.get_root() will return the head node of the tree.

Example 1:

Input: inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
Output: [null,1,[1,2]]

Example 2:

Input: inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
Output: [null,3,4,[1,2,3,4,5,6,7,8]]

Note:

  1. The initial given tree is complete and contains between 1 and 1000 nodes.
  2. CBTInserter.insert is called at most 10000 times per test case.
  3. Every value of a given or inserted node is between 0 and 5000.

这道题说是让实现一个完全二叉树的插入器的类,之前也做过关于完全二叉树的题 [Count Complete Tree Nodes](http://www.cnblogs.com/grandyang/p/4567827.html)。首先需要搞清楚的是完全二叉树的定义,即对于一颗二叉树,假设其深度为d(d>1)。除了第d层外,其它各层的节点数目均已达最大值,且第d层所有节点从左向右连续地紧密排列,换句话说,完全二叉树从根结点到倒数第二层满足完美二叉树,最后一层可以不完全填充,其叶子结点都靠左对齐。由于插入操作要找到最后一层的第一个空缺的位置,所以很自然的就想到了使用层序遍历的方法,由于插入函数返回的是插入位置的父结点,所以在层序遍历的时候,只要遇到某个结点的左子结点或者右子结点不存在,则跳出循环,则这个残缺的父结点刚好就在队列的首位置。那么在插入函数时,只要取出这个残缺的父结点,判断若其左子结点不存在,说明新的结点要连接在左子结点上,否则将新的结点连接在右子结点上,并把此时的左右子结点都存入队列中,并将之前的队首元素移除队列即可,参见代码如下:


解法一:

class CBTInserter {
public:
CBTInserter(TreeNode* root) {
tree_root = root;
q.push(root);
while (!q.empty()) {
auto t = q.front();
if (!t->left || !t->right) break;
q.push(t->left);
q.push(t->right);
q.pop();
}
}
int insert(int v) {
TreeNode *node = new TreeNode(v);
auto t = q.front();
if (!t->left) t->left = node;
else {
t->right = node;
q.push(t->left);
q.push(t->right);
q.pop();
}
return t->val;
}
TreeNode* get_root() {
return tree_root;
} private:
TreeNode *tree_root;
queue<TreeNode*> q;
};

下面这种解法缩短了建树的时间,但是极大的增加了插入函数的运行时间,因为每插入一个结点,都要从头开始再遍历一次,并不是很高效,可以当作一种发散思维吧,参见代码如下:


解法二:

class CBTInserter {
public:
CBTInserter(TreeNode* root) {
tree_root = root;
}
int insert(int v) {
queue<TreeNode*> q{{tree_root}};
TreeNode *node = new TreeNode(v);
while (!q.empty()) {
auto t = q.front(); q.pop();
if (t->left) q.push(t->left);
else {
t->left = node;
return t->val;
}
if (t->right) q.push(t->right);
else {
t->right = node;
return t->val;
}
}
return 0; }
TreeNode* get_root() {
return tree_root;
} private:
TreeNode *tree_root;
};

再来看一种不使用队列的解法,因为队列总是要遍历,比较麻烦,如果使用数组来按层序遍历的顺序保存这个完全二叉树的结点,将会变得十分的简单。而且有个最大的好处是,可以直接通过坐标定位到其父结点的位置,通过 (i-1)/2 来找到父结点,这样的话就完美的解决了插入函数要求返回父结点的要求,而且通过判断当前完整二叉树结点个数的奇偶,可以得知最后一个结点是在左子结点上还是右子结点上,这样就可以直接将新加入的结点连到到父结点的正确的子结点位置,参见代码如下:


解法三:

class CBTInserter {
public:
CBTInserter(TreeNode* root) {
tree.push_back(root);
for (int i = 0; i < tree.size(); ++i) {
if (tree[i]->left) tree.push_back(tree[i]->left);
if (tree[i]->right) tree.push_back(tree[i]->right);
}
}
int insert(int v) {
TreeNode *node = new TreeNode(v);
int n = tree.size();
tree.push_back(node);
if (n % 2 == 1) tree[(n - 1) / 2]->left = node;
else tree[(n - 1) / 2]->right = node;
return tree[(n - 1) / 2]->val;
}
TreeNode* get_root() {
return tree[0];
} private:
vector<TreeNode*> tree;
};

Github 同步地址:

https://github.com/grandyang/leetcode/issues/919

类似题目:

Count Complete Tree Nodes

参考资料:

https://leetcode.com/problems/complete-binary-tree-inserter/

https://leetcode.com/problems/complete-binary-tree-inserter/discuss/178424/C%2B%2BJavaPython-O(1)-Insert

https://leetcode.com/problems/complete-binary-tree-inserter/discuss/178528/Java-Solution%3A-O(1)-Insert-VS.-O(1)-Pre-process-Trade-Off

https://leetcode.com/problems/complete-binary-tree-inserter/discuss/178427/Java-BFS-straightforward-code-two-methods-Initialization-and-insert-time-O(1)-respectively.

[LeetCode All in One 题目讲解汇总(持续更新中...)](https://www.cnblogs.com/grandyang/p/4606334.html)

[LeetCode] 919. Complete Binary Tree Inserter 完全二叉树插入器的更多相关文章

  1. LeetCode 919. Complete Binary Tree Inserter

    原题链接在这里:https://leetcode.com/problems/complete-binary-tree-inserter/ 题目: A complete binary tree is a ...

  2. 【LeetCode】919. Complete Binary Tree Inserter 解题报告(Python & C++)

    作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址: https://leetcode. ...

  3. leetcode_919. Complete Binary Tree Inserter_完全二叉树插入

    https://leetcode.com/problems/complete-binary-tree-inserter/ 给出树节点的定义和完全二叉树插入器类的定义,为这个类补全功能.完全二叉树的定义 ...

  4. [Swift]LeetCode919. 完全二叉树插入器 | Complete Binary Tree Inserter

    A complete binary tree is a binary tree in which every level, except possibly the last, is completel ...

  5. PAT 1110 Complete Binary Tree[判断完全二叉树]

    1110 Complete Binary Tree(25 分) Given a tree, you are supposed to tell if it is a complete binary tr ...

  6. leetcode_919. Complete Binary Tree Inserter

    https://leetcode.com/problems/complete-binary-tree-inserter/ 设计一个CBTInserter,使用给定完全二叉树初始化.三个功能; CBTI ...

  7. PAT A1110 Complete Binary Tree (25 分)——完全二叉树,字符串转数字

    Given a tree, you are supposed to tell if it is a complete binary tree. Input Specification: Each in ...

  8. [二叉树建树&完全二叉树判断] 1110. Complete Binary Tree (25)

    1110. Complete Binary Tree (25) Given a tree, you are supposed to tell if it is a complete binary tr ...

  9. PAT甲级——1110 Complete Binary Tree (完全二叉树)

    此文章同步发布在CSDN上:https://blog.csdn.net/weixin_44385565/article/details/90317830   1110 Complete Binary ...

随机推荐

  1. 机器学习(九)-------- 聚类(Clustering) K-均值算法 K-Means

    无监督学习 没有标签 聚类(Clustering) 图上的数据看起来可以分成两个分开的点集(称为簇),这就是为聚类算法. 此后我们还将提到其他类型的非监督学习算法,它们可以为我们找到其他类型的结构或者 ...

  2. 重温CLR(十八) 运行时序列化

    序列化是将对象或对象图转换成字节流的过程,反序列化是将字节流转换回对象图的过程.在对象和字节流之间转换是很有用的机制. 1 应用程序的状态(对象图)可轻松保存到磁盘文件或数据库中,并在应用程序下次运行 ...

  3. Vertx和Jersey集成使用

    为了更好地解耦和提高性能,一般将工程的接口部分剥离出来形成一个单独的工程,这样不仅能提高性能,增强可维护性,并且在后台工程宕掉的话对客户端接口的影响较小. 公司使用了Vertx和Jersey,Vert ...

  4. docfx 简单使用方法、自动生成目录的工具

    [摘要] 这是我编写的一个 Docfx 文档自动生成工具,只要写好 Markdown 文档,使用此工具可为目录.文件快速生成配置,然后直接使用 docfx 运行即可. https://github.c ...

  5. 阿里Jvm必问面试题及答案

    什么是Java虚拟机?为什么Java被称作是“平台无关的编程语言”? Java虚拟机是一个可以执行Java字节码的虚拟机进程.Java源文件被编译成能被Java虚拟机执行的字节码文件. Java被设计 ...

  6. Java面试复习(纯手打)

    1.面向对象和面向过程的区别: 面向过程比面向对象高.因为类调用时需要实例化,开销比较大,比较消耗资源,所以当性能是最重要的考量因素得时候,比如单片机.嵌入式开发.Linux/Unix等一般采用面向过 ...

  7. 腾讯WeTest携手拉夏贝尔共筑电商小程序安全壁垒

    上海拉夏贝尔服饰股份有限公司成立于1998年,是中国快速发展的多品牌时尚运营企业.La Chapelle品牌创立初衷正是希望通过精美别致的时装设计,将法式优雅精致的风情元素和对生活的认知感悟传递给都市 ...

  8. 二叉搜索树(BST)基本操作

    什么是二叉搜索树? 二叉搜索树也叫做二叉排序树.二叉查找树,它有以下性质: 若任意节点的左子树不空,则左子树上所有节点的值均小于它的根节点的值: 若任意节点的右子树不空,则右子树上所有节点的值均大于它 ...

  9. Fundebug 微信小游戏异常监控插件更新至 0.5.0,支持监控 HTTP 慢请求

    摘要: 支持监控 HTTP 慢请求,同时修复了记录的 HTTP 响应时间偏小的 BUG. Fundebug是专业微信小游戏 BUG 监控服务,可以第一时间捕获线上环境中小游戏的异常.错误或者 BUG, ...

  10. python 自带模块 os模块

    os模块 首先可以打开cmd输入python进入交互界面  然后输入 dir(os) 就可以看到os的全部用法了  我们简单的举几个例子就行了. 写入os.getcwd()  可以查看当前所在路径 i ...