python中树,二叉树和二叉搜索树的实现差异

时间:2015-06-24 21:36:14

标签: python tree binary-tree binary-search-tree

我在掌握简单树,二叉树和二叉搜索树的方法和实现方面的差异时遇到了一些困难。似乎我一直在三者之间感到困惑。我知道如何实施BST。但是,我不太确定简单的树和二叉树。有人可以告诉我一个简单的树实现/代码和BT。 P.S这不是功课,它让我理解这些ADT的

这是BST的代码,我有。

“”“二分查找树ADT”“”

class BST:

def __init__(self: 'BST', root: BTNode=None) -> None:
    """Create BST with BTNode root."""
    self._root = root

def __repr__(self: 'BST') -> str:
    """Represent this binary search tree."""
    return 'BST(' + repr(self._root) + ')'

def find(self: 'BST', data: object) -> BTNode:
    """Return node containing data, otherwise return None."""
    return _find(self._root, data)

def insert(self: 'BST', data: object) -> None:
    """Insert data, if necessary, into this tree.

    >>> b = BST()
    >>> b.insert(8)
    >>> b.insert(4)
    >>> b.insert(2)
    >>> b.insert(6)
    >>> b.insert(12)
    >>> b.insert(14)
    >>> b.insert(10)
    >>> b
    BST(BTNode(8, BTNode(4, BTNode(2, None, None), BTNode(6, None, None)), BTNode(12, BTNode(10, None, None), BTNode(14, None, None))))
"""
    self._root = _insert(self._root, data)

def height(self: 'BST') -> int:
    """Return height of this tree."""
    return _height(self._root)

def _insert(node: BTNode, data: object) -> BTNode:
    """Insert data in BST rooted at node, if necessary, and return root."""
    if not node:
        return BTNode(data)
    elif data < node.data:
        node.left = _insert(node.left, data)
    elif data > node.data:
        node.right = _insert(node.right, data)
    else:  # nothing to do
        pass
return node

def _find(node: BTNode, data: object):
    """Return the node containing data, or else None."""
    if not node or node.data == data:
        return node
    else:
        if data < node.data:
            return _find(node.left, data)
        else:
            return _find(node.right, data)

def _height(node):
    """Return height of tree rooted at node."""
    if not node or node.is_leaf():
        return 0
    left_h = 0
    right_h = 0
    if node.left:
        left_h = _height(node.left)
    if node.right:
        right_h = _height(node.right)
    return max(left_h, right_h) + 1    

class BTNode:
"""Binary Tree node."""

def __init__(self: 'BTNode', data: object,
             left: 'BTNode'=None, right: 'BTNode'=None) -> None:
    """Create BT node with data and children left and right."""
    self.data, self.left, self.right = data, left, right

def __repr__(self: 'BTNode') -> str:
    """Represent this node as a string."""
    return ('BTNode(' + str(self.data) + ', ' + repr(self.left) +
            ', ' + repr(self.right) + ')')

def is_leaf(self: 'BTNode') -> bool:
    """Return True iff BTNode is a leaf"""
    return not self.left and not self.right

1 个答案:

答案 0 :(得分:2)

  1. 一棵树,每个节点可以有任意数量的子节点,它当然不需要平衡。

  2. 二叉树,是一个树,每个节点可以有0..2个孩子

  3. 一个BST,与二叉树相同,但保证左边的节点小于当前节点,而节点右边更大......