【LeetCode】919. Complete Binary Tree Inserter 解题报告(Python & C++)
作者: 负雪明烛
id: fuxuemingzhu
个人博客: http://fuxuemingzhu.cn/
题目地址: https://leetcode.com/problems/complete-binary-tree-inserter/description/
题目描述
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:
- The initial given tree is complete and contains between 1 and 1000 nodes.
- CBTInserter.insert is called at most 10000 times per test case.
- Every value of a given or inserted node is between 0 and 5000.
题目大意
编写一个完全二叉树的数据结构,需要完成构建、插入、获取root三个函数。函数的参数和返回值如题。
解题方法
周赛第三题,因为第二题我不会,就把这个题给放弃了……现在一看很简单啊。
完全二叉树是每一层都满的,因此找出要插入节点的父亲节点是很简单的。如果用数组tree保存着所有节点的层次遍历,那么新节点的父亲节点就是tree[(N -1)/2],N是未插入该节点前的树的元素个数。
构建树的时候使用层次遍历,也就是BFS把所有的节点放入到tree里。插入的时候直接计算出新节点的父亲节点。获取root就是数组中的第0个节点。
时间复杂度是O(N),空间复杂度是O(N)。
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class CBTInserter(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.tree = list()
queue = collections.deque()
queue.append(root)
while queue:
node = queue.popleft()
self.tree.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
def insert(self, v):
"""
:type v: int
:rtype: int
"""
_len = len(self.tree)
father = self.tree[(_len - 1) / 2]
node = TreeNode(v)
if not father.left:
father.left = node
else:
father.right = node
self.tree.append(node)
return father.val
def get_root(self):
"""
:rtype: TreeNode
"""
return self.tree[0]
# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(v)
# param_2 = obj.get_root()
C++代码如下:
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class CBTInserter {
public:
CBTInserter(TreeNode* root) {
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
TreeNode* node = q.front(); q.pop();
if (!node) continue;
tree.push_back(node);
q.push(node->left);
q.push(node->right);
}
}
int insert(int v) {
TreeNode* node = new TreeNode(v);
tree.push_back(node);
TreeNode* parent = tree[tree.size() / 2 - 1];
if (!parent->left)
parent->left = node;
else
parent->right = node;
return parent->val;
}
TreeNode* get_root() {
return tree[0];
}
private:
vector<TreeNode*> tree;
};
/**
* Your CBTInserter object will be instantiated and called as such:
* CBTInserter* obj = new CBTInserter(root);
* int param_1 = obj->insert(v);
* TreeNode* param_2 = obj->get_root();
*/
日期
2018 年 10 月 7 日 —— 假期最后一天!!
2018 年 12 月 11 日 —— 双十一已经过去一个月了,真快啊。。
【LeetCode】919. Complete Binary Tree Inserter 解题报告(Python & C++)的更多相关文章
- [LeetCode] 919. Complete Binary Tree Inserter 完全二叉树插入器
A complete binary tree is a binary tree in which every level, except possibly the last, is completel ...
- LeetCode 919. Complete Binary Tree Inserter
原题链接在这里:https://leetcode.com/problems/complete-binary-tree-inserter/ 题目: A complete binary tree is a ...
- 【LeetCode】968. Binary Tree Cameras 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 日期 题目地址:https://leetcode.c ...
- 【LeetCode】563. Binary Tree Tilt 解题报告(Java & Python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 Java解法 Python解法 日期 题目地址:ht ...
- 【LeetCode】257. Binary Tree Paths 解题报告(java & python)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 迭代 日期 题目地址:https://leet ...
- 【LeetCode】814. Binary Tree Pruning 解题报告(Python & C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 后序遍历 日期 题目地址:https://leetc ...
- [Swift]LeetCode919. 完全二叉树插入器 | Complete Binary Tree Inserter
A complete binary tree is a binary tree in which every level, except possibly the last, is completel ...
- 【LeetCode】998. Maximum Binary Tree II 解题报告(C++)
作者: 负雪明烛 id: fuxuemingzhu 个人博客: http://fuxuemingzhu.cn/ 目录 题目描述 题目大意 解题方法 递归 日期 题目地址:https://leetcod ...
- LeetCode 104. Maximum Depth of Binary Tree C++ 解题报告
104. Maximum Depth of Binary Tree -- Easy 方法 使用递归 /** * Definition for a binary tree node. * struct ...
随机推荐
- 43-Reverse Nodes in k-Group
Reverse Nodes in k-Group My Submissions QuestionEditorial Solution Total Accepted: 58690 Total Submi ...
- phpexcel 另存Excel文件方式
$w = new PHPExcel_Writer_Excel5($e); $dir = 'path/title.xls'; $w->save($dir);
- Kafka入门教程(一)
转自:https://blog.csdn.net/yuan_xw/article/details/51210954 1 Kafka入门教程 1.1 消息队列(Message Queue) Messag ...
- Stream.toMap
Collectors类的tomap方法将流收集到映射实例中. list 转 map collection.stream().collect(Collectors.toMap(User::getId, ...
- android studio 使用 aidl(三)权限验证
这篇文章是基于android studio 使用 aidl (一) 和 android studio 使用 aidl(二) 异步回调 下面的代码都是简化的,如果看不懂请先移步上2篇文章 网上的东西太坑 ...
- Apache架构师的30条设计原则
本文作者叫 Srinath,是一位科学家,软件架构师,也是一名在分布式系统上工作的程序员. 他是 Apache Axis2 项目的联合创始人,也是 Apache Software 基金会的成员. 他是 ...
- hadoop accesscontrolException
DFS loaction: /tmp 文件下的 hadoop-haoop/mapred/system报 AccessControlException. 解决: bin/hadoop fs -chmod ...
- 基于阿里云ecs(centos 7) 安装jenkins
1. 安装好 jdk 2. 官网(https://pkg.jenkins.io/redhat-stable/)下载rpm包(稳定版): wget https://pkg.jenkins.io/redh ...
- request获取请求参数通用方式
package com.hopetesting.web.request;import javax.servlet.ServletException;import javax.servlet.annot ...
- python的urllib学习
1.基本方法 urllib.request.urlopen(url, data=None, [timeout, ]*, cafile=None, capath=None, cadefault=Fals ...