层序遍历-递归法:
# 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 = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
queue = collections.deque()
queue.append(root)
times = 0
while queue:
for i in range(len(queue)):
times += 1
node = queue.popleft()
if node.left: queue.append(node.left)
if node.right: queue.append(node.right)
return times
依次求左右子树节点数-递归法:
# 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 = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
return self.getVal(root)
def getVal(self, root: 'TreeNode'):
if not root: return 0
left = self.getVal(root.left)
right = self.getVal(root.right)
return left + right + 1
依次求左右子树节点个数法,递归法
# 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 = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
left = root.left
right = root.right
leftDepth, rightDepth = 0, 0
while left:
left = left.left
leftDepth += 1
while right:
right = right.right
rightDepth += 1
if leftDepth == rightDepth:
return ( 2 << rightDepth ) - 1
leftDepth = self.countNodes(root.left)
rightDepth = self.countNodes(root.right)
return leftDepth + rightDepth + 1
思路:
依次计算根节点的左右孩子节点数。
1.若该根节点所在树为满二叉树,则用公式2^层数=节点数 计算
2.若不满足满二叉树,则如法炮制,分而治之:依次计算该节点的左右子树的节点数。若为满二叉树则用公式,否则继续如法炮制。
递归的三部曲:
1.递归函数参数root和返回值int:
2.递归结束条件,判断根节点所在树是否为满二叉树(左子树与右子树深度是否相同)
3.单层递归逻辑:若不满足满二叉树,则继续如法炮制,分而治之。
精简版:
# 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 = right
class Solution:
def countNodes(self, root: Optional[TreeNode]) -> int:
if not root: return 0
left = root.left
right = root.right
leftDepth, rightDepth = 0, 0
while left:
left = left.left
leftDepth += 1
while right:
right = right.right
rightDepth += 1
if leftDepth == rightDepth:
return ( 2 << rightDepth ) - 1
# 精简在这里了!!
return self.countNodes(root.left) + self.countNodes(root.right) + 1