解题思路需要保持树的节点数和高度。树的高度h=math.floor(math.log(节点数,2)+1)每次插入:计算当前叶子节点数(leaf_cnt=int(cnt-2**(h-1)+1)),当前最后一层叶子节点的最大个数(full_leaf_cnt=int(2**(h-1)))如果当前叶子节点个数为0到最大个数//2,或者叶子节点满了,向左递归如果子树没有递归到右子树,则递归退出条件为:子树的节点数==1,直接插入当前节点的左孩子,并且节点数==2,将其作为右孩子插入。代码#定义二叉树节点。#classTreeNode:#def__init__(self,x):#self.val=x#self.left=None#self.right=NoneclassCBTInserter:def__init__(self,root:TreeNode):self.root=rootself.cnt=0self.get_cnt(root)self.h=math.floor(math.log(self.cnt,2)+1)defget_cnt(self,root):ifroot:self.cnt+=1self.get_cnt(root.left)self.get_cnt(root.right)definsert(self,v:int)->int:ifself.cnt==0:self.root=TreeNode(v)否则:返回self.do_insert(v,self.cnt,self.h,self.root)defdo_insert(self,v,cnt,h,r):如果cnt==1:r.left=TreeNode(v)self.cnt+=1self.h=math.floor(math.log(self.cnt,2)+1)返回r.valelifcnt==2:r.right=TreeNode(v)self.cnt+=1self.h=数学.floor(math.log(self.cnt,2)+1)returnr.valelse:leaf_cnt=int(cnt-2**(h-1)+1)#当前叶子节点个数full_leaf_cnt=int(2**(h-1))#最后一层最大叶节点数ifleaf_cnt==full_leaf_cnt:returnself.do_insert(v,2**(h-1)-1,h-1,r.left)elifleaf_cnt
