要求
完全二叉树是每一层(除最后一层外)都是完全填充(即,节点数达到最大)的,并且所有的节点都尽可能地集中在左侧。
设计一个用完全二叉树初始化的数据结构 CBTInserter,它支持以下几种操作:
- CBTInserter(TreeNode root) 使用头节点为 root 的给定树初始化该数据结构;
- CBTInserter.insert(int v) 向树中插入一个新节点,节点类型为 TreeNode,值为 v 。使树保持完全二叉树的状态,并返回插入的新节点的父节点的值;
- CBTInserter.get_root() 将返回树的头节点。
示例 1:
输入:inputs = ["CBTInserter","insert","get_root"], inputs = [[[1]],[2],[]]
输出:[null,1,[1,2]]
示例 2:
输入:inputs = ["CBTInserter","insert","insert","get_root"], inputs = [[[1,2,3,4,5,6]],[7],[8],[]]
输出:[null,3,4,[1,2,3,4,5,6,7,8]]
提示:
- 最初给定的树是完全二叉树,且包含 1 到 1000 个节点。
- 每个测试用例最多调用 CBTInserter.insert 操作 10000 次。
- 给定节点或插入节点的每个值都在 0 到 5000 之间。
核心代码
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class CBTInserter:
def __init__(self, root: TreeNode):
self.node_list = [None]
queue = [root]
while queue:
node = queue.pop(0)
self.node_list.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
def insert(self, val: int) -> int:
self.node_list.append(TreeNode(val))
idx = len(self.node_list) - 1
father = self.node_list[idx // 2]
if idx %2 == 0:
father.left = self.node_list[-1]
else:
father.right = self.node_list[-1]
return father.val
def get_root(self) -> TreeNode:
return self.node_list[1]
# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(val)
# param_2 = obj.get_root()
解题思路:这是一道数据结构构造的问题,主要是考虑完全二叉树中index的关系,按照指定的index去构造完全二叉树即可。