qcode
  • 创作工场专业版,一问多答!更智能、更完整、更原创
  • 这是一个超强内容创作平台,它会写文章、做设计、绘图、敲代码,有问必答!
🔥点击使用-免登录深度版🔥

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

时间2023-06-20 16:06:27 提问来自 福建省福州市 的网友 分类创作 浏览261
采用全局变量方式: ```python count = 0 # 全局变量,记录度为2的结点个数 def count_degree_2(root): global count if root is None: return if root.left and root.right: # 如果左右子树都存在,则该结点度为2 count += 1 count_degree_2(root.left) count_degree_2(root.right) ``` 采用函数返回值方式: ```python 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: # 如果左右子树都存在,则该结点度为2 return left_count + right_count + 1 else: return left_count + right_count ``` 以上两种方式都是基于二叉树的遍历实现的,时间复杂度为O(n),其中n为二叉树的结点个数。

不满意?免费深度重写!

免责声明:
以上内容除特别注明外均来源于网友提问,创作工场回答,未经许可,严谨转载。

上一篇 谈谈你这学期学习形势与政策的心得 下一篇 发条橙 A Clockwork Orange影评