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.
分析
题目的意思是:实现一个完全二叉树的插入操作,这道题需要用到队列,先遍历到要插入的位置然后插入就行了,那么可以用队列q1存入插入的位置的父节点。首先,需要找到父结点,利用队列q2,进入队列的顺序是从左到右,找到缺少叶子结点的结点就行了,然后就存入到先前的队列q1。插入的时候也是先插入左叶子结点,如果位置是右结点的话,q1需要把当前的结点移除,表明该结点不需要再插入任何结点了。
代码
# 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.root=root
self.deque=collections.deque()
q=[self.root]
while(q):
node=q.pop(0)
if(not node.left or not node.right):
self.deque.append(node)
if(node.left):
q.append(node.left)
if(node.right):
q.append(node.right)
def insert(self, v: int) -> int:
node=self.deque[0]
self.deque.append(TreeNode(v))
if(node.left is None):
node.left=self.deque[-1]
elif(node.right is None):
node.right=self.deque[-1]
self.deque.popleft()
return node.val
def get_root(self) -> TreeNode:
return self.root
# Your CBTInserter object will be instantiated and called as such:
# obj = CBTInserter(root)
# param_1 = obj.insert(v)
# param_2 = obj.get_root()