【发布时间】:2020-02-21 05:17:12
【问题描述】:
我必须递归地计算二叉树中的节点。我是 python 新手,找不到任何解决方案来完成我的代码。
这是我已经尝试过的。如您所见,它不完整,我不知道该去哪里。
class Tree:
def __init__(self, root):
self.root = root
def add(self, subtree):
self.root.children.append(subtree)
class Node:
def __init__(self, value, children=None):
self.value = value
self.children = children if children is not None else []
def check_root(tree):
if tree.root is None:
return 0
if tree.root is not None:
return count_nodes(tree)
def count_nodes(tree):
if tree.root.children is not None:
j = 0
for i in tree.root.children:
j = 1 + count_nodes(tree)
return j
print(count_nodes(Tree(None))) # 0
print(count_nodes(Tree(Node(10)))) # 1
print(count_nodes(Tree(Node(5, [Node(6), Node(17)])))) #3
每迈出新的一步,我都会遇到不同的错误。例如。使用此代码,我已经超过了最大递归深度。
感谢您抽出宝贵时间阅读本文。任何提示或帮助下一步做什么将不胜感激。
【问题讨论】:
标签: python recursion binary-tree