我对数据结构和递归相当陌生。因此,我决定尝试实现一种方法,该方法将在此给定树中打印右侧子树的所有节点的所有值(按升序排列,即:50,65,72,91,99),就像学习经验一样。
这是我正在使用的树,视觉上。
我在理解如何通过正确的子树递归方面遇到了很多问题。
这就是我到目前为止尝试过的方法(实际方法在底部):
class BinarySearchTree:
_root: Optional[Any]
# The left subtree, or None if the tree is empty.
_left: Optional[BinarySearchTree]
# The right subtree, or None if the tree is empty.
_right: Optional[BinarySearchTree]
def __init__(self, root: Optional[Any]) -> None:
"""Initialize a new BST containing only the given root value.
"""
if root is None:
self._root = None
self._left = None
self._right = None
else:
self._root = root
self._left = BinarySearchTree(None)
self._right = BinarySearchTree(None)
def is_empty(self) -> bool:
"""Return True if this BST is empty.
>>> bst = BinarySearchTree(None)
>>> bst.is_empty()
True
"""
return self._root is None
# That is what I have tried doing so far.
def print_right_subtree(self) -> None:
"""Print the right subtree in order
>>> bst = BinarySearchTree(41)
>>> left = BinarySearchTree(20)
>>> left._left = BinarySearchTree(11)
>>> left._right = BinarySearchTree(29)
>>> left._right._right = BinarySearchTree(32)
>>> right = BinarySearchTree(65)
>>> right._left = BinarySearchTree(50)
>>> right._right = BinarySearchTree(91)
>>> right._right._left = BinarySearchTree(72)
>>> right._right._right = BinarySearchTree(99)
>>> bst._left = left
>>> bst._right = right
>>> bst.print_right_subtree()
50
65
72
91
99
"""
if self.is_empty():
pass
else:
# I am not really sure what to do here...
# I have tried setting self._left = None, but that just made things even more complicated!
print(self._root)
self._right.print_right_subtree()
任何帮助将不胜感激!另外,如果你们中的任何一个人有一个我可以遵循的教程,那对于像我这样的新手来说真的很棒,:)。
温温酱
智慧大石
相关分类