统计二叉树的结点个数,可以使用递归或迭代的方法。下面是两种常见的实现方式:
✅ 1. 递归方法(最常见)
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_nodes(root):
if not root:
return 0
return 1 + count_nodes(root.left) + count_nodes(root.right)
示例:
# 创建一个二叉树
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(count_nodes(root)) # 输出: 5
✅ 2. 迭代方法(非递归)
def count_nodes_iterative(root):
if not root:
return 0
stack = [root]
count = 0
while stack:
node = stack.pop()
count += 1
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return count
示例:
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
root.left.right = TreeNode(5)
print(count_nodes_iterative(root)) # 输出: 5
✅ 3. 使用 BFS(广度优先搜索)
def count_nodes_bfs(root):
if not root:
return 0
queue = [root]
count = 0
while queue:
node = queue.pop(0)
count += 1
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
return count
总结:
| 方法 | 时间复杂度 | 空间复杂度 |
|---|---|---|
| 递归 | O(n) | O(h) |
| 迭代(栈) | O(n) | O(h) |
| 迭代(队列) | O(n) | O(h) |
✅ 最终
如果你需要一个函数来统计二叉树的结点个数,可以使用如下代码:
class TreeNode:
def __init__(self, val=0, left=None, right=None):
self.val = val
self.left = left
self.right = right
def count_nodes(root):
if not root:
return 0
return 1 + count_nodes(root.left) + count_nodes(root.right)
或者使用迭代方式:
def count_nodes(root):
if not root:
return 0
stack = [root]
count = 0
while stack:
node = stack.pop()
count += 1
if node.left:
stack.append(node.left)
if node.right:
stack.append(node.right)
return count
如果你有具体的二叉树结构,也可以告诉我,我可以帮你计算具体结点数。