当前位置: 首页 > 后端技术 > Python

leetcode919.完全二叉树插入器-python递归求解

时间:2023-03-25 19:47:40 Python

解题思路需要保持树的节点数和高度。树的高度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>1:returnself.do_insert(v,2**(h-2)-1+leaf_cnt,h-1,r.left)else:returnself.do_insert(v,2**(h-2)-1+leaf_cnt-(full_leaf_cnt>>1),h-1,r.right)defget_root(self)->TreeNode:returnself.root#你的CBTInserter对象将被实例化并这样调用:#obj=CBTInserter(root)#param_1=obj.insert(v)#param_2=obj.get_root()另一种解决方法:建一个双向队列,只把子节点不满足的节点放入队列。当一个节点的右孩子被插入时,它就会出队。https://leetcode-cn.com/probl...欢迎来到我的博客:https://codeplot.top/我的博客问题分类:https://codeplot.top/categories/%E5%88%B7%E9%A2%98/