# 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 = rightclassCBTInserter:def__init__(self,root:Optional[TreeNode]):self.tree=[]q=deque([root])whileq:for_inrange(len(q)):node=q.popleft()self.tree.append(node)ifnode.left:q.append(node.left)ifnode.right:q.append(node.right)definsert(self,val:int)->int:p=self.tree[(len(self.tree)-1)//2]node=TreeNode(val)self.tree.append(node)ifp.leftisNone:p.left=nodeelse:p.right=nodereturnp.valdefget_root(self)->Optional[TreeNode]:returnself.tree[0]# Your CBTInserter object will be instantiated and called as such:# obj = CBTInserter(root)# param_1 = obj.insert(val)# param_2 = obj.get_root()
/** * Definition for a binary tree node. * type TreeNode struct { * Val int * Left *TreeNode * Right *TreeNode * } */typeCBTInserterstruct{tree[]*TreeNode}funcConstructor(root*TreeNode)CBTInserter{q:=[]*TreeNode{root}tree:=[]*TreeNode{}forlen(q)>0{fori:=len(q);i>0;i--{node:=q[0]q=q[1:]tree=append(tree,node)ifnode.Left!=nil{q=append(q,node.Left)}ifnode.Right!=nil{q=append(q,node.Right)}}}returnCBTInserter{tree}}func(this*CBTInserter)Insert(valint)int{p:=this.tree[(len(this.tree)-1)/2]node:=&TreeNode{val,nil,nil}this.tree=append(this.tree,node)ifp.Left==nil{p.Left=node}else{p.Right=node}returnp.Val}func(this*CBTInserter)Get_root()*TreeNode{returnthis.tree[0]}/** * Your CBTInserter object will be instantiated and called as such: * obj := Constructor(root); * param_1 := obj.Insert(val); * param_2 := obj.Get_root(); */
/* public class TreeNode {* public var val: Int* public var left: TreeNode?* public var right: TreeNode?* public init() { self.val = 0; self.left = nil; self.right = nil; }* public init(_ val: Int) { self.val = val; self.left = nil; self.right = nil; }* public init(_ val: Int, _ left: TreeNode?, _ right: TreeNode?) {* self.val = val* self.left = left* self.right = right* }* }*/classCBTInserter{privatevartree:[TreeNode]=[]init(_root:TreeNode?){guardletroot=rootelse{return}varq:[TreeNode]=[root]while!q.isEmpty{for_in0..<q.count{letnode=q.removeFirst()tree.append(node)ifletleft=node.left{q.append(left)}ifletright=node.right{q.append(right)}}}}funcinsert(_val:Int)->Int{letp=tree[(tree.count-1)/2]letnode=TreeNode(val)tree.append(node)ifp.left==nil{p.left=node}else{p.right=node}returnp.val}funcget_root()->TreeNode?{returntree.isEmpty?nil:tree[0]}}/** * Your CBTInserter object will be instantiated and called as such: * let obj = CBTInserter(root) * let param_1 = obj.insert(val) * let param_2 = obj.get_root() */