【发布时间】:2021-03-02 12:26:08
【问题描述】:
我需要在三个定义中实现一个函数,并且我最初创建了一个固定长度为 512 的空二叉树构造函数来保存三个定义中的元素。
这是我的空二叉树构造函数:
def __init__(self):
self._maxArraySize = 512
self._array = [None]*self._maxArraySize
self._size = 0
困难的部分是我需要实现一个函数,该函数将元素 e 放在一棵空树的根部,并返回根在 _add_root 中的位置
在 _add_left 函数中,它应该将元素 e 放在 p 的左孩子中并返回孩子的位置
最后,_add_right 函数应该将元素 e 放在 p 的右孩子中,并返回孩子的位置。
我完成但不起作用的代码如下所示,除了非公开的修改器之外,所有内容都给出了。
from binary_tree import BinaryTree
class ArrayBinaryTree(BinaryTree):
"""List representation of a binary tree structure."""
#-------------------------- nested Position class --------------------------
class Position(BinaryTree.Position):
"""An abstraction representing the location of a single element."""
def __init__(self, container, arrayIndex):
"""Constructor should not be invoked by user."""
self._container = container
self._arrayIndex = arrayIndex
def element(self):
"""Return the element stored at this Position."""
if self._arrayIndex > self._container._maxArraySize:
raise ValueError('invalid position')
return self._container._array[self._arrayIndex]
def __eq__(self, other):
"""Return True if other is a Position representing the same location."""
return type(other) is type(self) and other._container is self._container and \
other._arrayIndex == self._arrayIndex
#------------------------------- utility methods -------------------------------
def _validate(self, p):
"""Return associated array index, if position is valid."""
if not isinstance(p, self.Position):
raise TypeError('p must be proper Position type')
if p._container is not self:
raise ValueError('p does not belong to this container')
return p._arrayIndex
def _make_position(self, arrayIndex):
"""Return Position instance for given array index."""
if arrayIndex >= self._maxArraySize:
return None
if self._array[arrayIndex] is None:
return None
return self.Position(self, arrayIndex)
def __init__(self):
"""Create an initially empty binary tree."""
self._maxArraySize = 512
self._array = [None]*self._maxArraySize
self._size = 0
#-------------------------- public accessors --------------------------
def __len__(self):
"""Return the total number of elements in the tree."""
# TODO: Implement the len() operator that returns the total number of elements
# in the tree.
return self._size
def root(self):
"""Return the root Position of the tree (or None if tree is empty)."""
# TODO: Implement the root function from the Tree base class.
# Return the root Position of the tree. Use _make_position to create
# the Position instance.
return self._make_position(self._array)
def parent(self, p):
"""Return the Position of p's parent (or None if p is root)."""
# TODO: Implement the parent function from the Tree base class.
# Return the Position of p's parent. Use _validate to get the
# index of p and _make_position to create the parent Position instance.
arrayIndex = self._validate(p)
return self._make_position(arrayIndex._parent)
def left(self, p):
"""Return the Position of p's left child (or None if no left child)."""
# TODO: Implement the left function from the BinaryTree base class.
# Return the Position of p's left child. Use _validate to get the
# index of p and _make_position to create the left child Position instance.
arrayIndex = self._validate(p)
return self._make_position(arrayIndex._left)
def right(self, p):
"""Return the Position of p's right child (or None if no right child)."""
# TODO: Implement the right function from the BinaryTree base class.
# Return the Position of p's right child. Use _validate to get the
# index of p and _make_position to create the right child Position instance.
arrayIndex = self._validate(p)
return self._make_position(arrayIndex._right)
def num_children(self, p):
"""Return the number of children of Position p."""
# TODO: Implement the num_children function from the Tree base class.
# Return the number of children of p. Use _validate to get the index or
# use left and right.
arrayIndex = self._validate(p)
count = 0
if arrayIndex._left is not None:
count += 1
if arrayIndex._right is not None:
count += 1
return count
#-------------------------- nonpublic mutators --------------------------
def _add_root(self, e):
"""Place element e at the root of an empty tree and return new Position.
Raise ValueError if tree nonempty.
"""
# TODO: Implement a function that places the element e at the root
# of an empty tree and returns the Position of the root. Use
# _make_position to create the Position instance.
if self._array is not None:
raise ValueError('Root exists')
self._size = 1
self._array = self._array(e)
return self._make_position(self._array)
def _add_left(self, p, e):
"""Create a new left child for Position p, storing element e.
Return the Position of new element.
Raise ValueError if Position p is invalid or p already has a left child.
"""
# TODO: implement a function that places the element e in the left child of
# p and returns the Position of the child. Use _validate to get the
# index of p and _make_position to create the left child Position instance.
arrayIndex = self._validate(p)
if arrayIndex._left is not None:
raise ValueError('Left child exists')
self._size += 1
arrayIndex._left = self._array(e, 2*p + 1)
return self._make_position(arrayIndex._left)
def _add_right(self, p, e):
"""Create a new right child for Position p, storing element e.
Return the Position of new element.
Raise ValueError if Position p is invalid or p already has a right child.
"""
# TODO: implement a function that places the element e in the right child of
# p and returns the Position of the child. Use _validate to get the
# index of p and _make_position to create the right child Position instance.
arrayIndex = self._validate(p)
if arrayIndex._right is not None:
raise ValueError('Left child exists')
self._size += 1
arrayIndex._right = self._array(e, 2*p + 2)
return self._make_position(arrayIndex._right)
谢谢//
【问题讨论】:
-
为什么方法名以下划线开头?习惯是,前导下划线表示该方法应该被视为私有方法,但您肯定希望允许您的实现用户添加节点...
-
_validate或_make_position的代码是什么?是否有您需要使用的样板代码? -
基于数组的树不需要节点类。如果父索引为
p,则左子索引为(2*p)+1,右子索引为(2*p)+2。 -
嗯,这不是很有效...你应该回复 cmets。继续...
-
@trincot 对不起,伙计,是的,_validate 和 _make_position 都有代码。如果位置有效,_validate 返回关联的数组索引。 _make_position 返回给定数组索引的位置实例。我可以将两个样板代码都放在问题中。
标签: python tree binary-tree root