222. 完全二叉树的节点个数
解法一:暴力递归
class Solution:
def countNodes(self, root: TreeNode) -> int:
if not root:
return 0
return self.countNodes(root.left) + self.countNodes(root.right) + 1二、利用完全二叉树性质
class Solution:
def countNodes(self, root: TreeNode) -> int:
l=root
hl=0
while l != None:
l = l.left
hl+=1
r=root
hr=0
while r != None:
r = r.right
hr+=1
if hl == hr:
return 2**hl - 1
return 1 + self.countNodes(root.left) + self.countNodes(root.right)最后更新于
