方法1
Deque: use deque to save the no-completed node, if a node become completed, remove it from deque
from collections import deque
# 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
queue = deque([root])
self.nodes = []
while queue:
node = queue.popleft()
if not node.left or not node.right:
self.nodes.append(node)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
def insert(self, v: int) -> int:
curt = self.nodes[0]
if not curt.left:
curt.left = TreeNode(v)
self.nodes.append(curt.left)
elif not curt.right:
curt.right = TreeNode(v)
self.nodes.append(curt.right)
self.nodes.pop(0)
return curt.val
def get_root(self) -> TreeNode:
return self.root