【发布时间】:2017-05-27 00:10:20
【问题描述】:
假设我们有一个类BinaryTree定义如下(不能修改):
class BinaryTree:
def __init__(self, value = None):
self.value = value
if self.value is not None:
self.left_node = BinaryTree()
self.right_node = BinaryTree()
else:
self.left_node = None
self.right_node = None
我有一个堆栈,由数字和'+'组成,例如,
stack = ['1', '2', '+', '3', '4', '5', '+', '+', '+']
现在我想构造二叉树。规则如下:
从右到左,根是'+'。
然后如果字符是'+',扩展分支,
否则,我们将数字从 left_node 添加到 right_node。
按照我弹出列表中最后一个元素的顺序,详细的流程说明如下:
t = BinaryTree('+')
t.left_node = BinaryTree('+')
t.left_node.left_node = BinaryTree('+')
t.left_node.left_node.left_node = BinaryTree('5')
t.left_node.left_node.right_node = BinaryTree('4')
t.left_node.right_node = BinaryTree('3')
t.right_node = BinaryTree('+')
t.right_node.left_node = BinaryTree('2')
t.right_node.right_node = BinaryTree('1')
我知道我需要使用递归和控制结构来解决这个问题,但我不确定如何将其应用于在树中添加节点。
如果有什么需要澄清的,请告诉我,我们将不胜感激。
【问题讨论】:
-
这看起来像是一个标准的介绍性数据结构问题。如果是家庭作业,您可能会发现 this Meta Stack Overflow topic 对提出这个问题很有用。
-
嗨,马修,感谢您的提醒。是的,这确实是我目前所坚持的家庭作业的一部分。
-
既然是家庭作业,你正在使用哪些算法课本(或者手头有上一堂课的课本)?科门?塞奇威克?
-
哦,我们没有教科书,讲师解释了二叉树,但这个挑战需要相当多的递归知识
标签: python recursion binary-tree