aiaiask.com©

开花即结果 提问即答案

编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数,并说明如何调用编写的函数
原始问题:

编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数,并说明如何调用编写的函数

采用全局变量方式:

count = 0  # 全局变量,用于记录度为2的结点个数

def count_degree_2(root):
    global count
    if root is None:
        return
    if root.left and root.right:
        count += 1
    count_degree_2(root.left)
    count_degree_2(root.right)

采用函数返回值方式:

def count_degree_2(root):
    if root is None:
        return 0
    left_count = count_degree_2(root.left)
    right_count = count_degree_2(root.right)
    if root.left and root.right:
        return left_count + right_count + 1
    else:
        return left_count + right_count

调用方式:

# 假设已经创建好了一棵二叉树,根节点为root
# 调用全局变量方式
count_degree_2(root)
print(count)  # 输出度为2的结点个数

# 调用函数返回值方式
degree_2_count = count_degree_2(root)
print(degree_2_count)  # 输出度为2的结点个数
编写递归算法,分别采用全局变量和函数返回值两种方式返回二叉树上度为2的结点个数,并说明如何调用编写的函数
https://www.aiaiask.com/ask/38376.html
AI / 模型Siliconflow
时间 / DATEJune 20, 2023, 4:25 PM
语言zh-CN
IP / 区域福建 福州