给定一棵完全二叉树的头节点head,返回这棵树的节点个数。
完全二叉树指:设二叉树的深度为h,则 [1,h-1] 层的节点数都满足 个
数据范围:节点数量满足 ,节点上每个值都满足
进阶:空间复杂度 , 时间复杂度
if not head: return 0 return self.nodeNum(head.left)+1+self.nodeNum(head.right) #递归
因为是完全二叉树,直接数最后一层的个数就行了,最后一层的个数等于2**height - (遇到的叶子节点个数) class Solution: count = 0 def nodeNum(self , head: TreeNode) -> int: # write code here def height(head): if not head: self.count += 1 return 0 return max(height(head.left), height(head.right)) + 1 h = height(head) ret = 0 for i in range(h): ret += 2**i lastLevel = 2**h return ret - (lastLevel - self.count)