Skip to main content
 首页 » 编程设计

python之如何在python中计算BST的高度

2025年05月04日1398°冷暖

我已经创建了一个 BST。现在我想找到开发的 BST 的高度。

这是我构建BST

的代码
class Node: 
    '''represents a new node in the BST''' 
    def __init__(self,key): 
        self.key=key 
        self.disconnect() 
    def disconnect(self): 
        self.left=None; 
        self.right=None; 
        self.parent=None; 
    def __str__(self): 
        return 'node with kay %s'%self.key 
 
class BST: 
    def __init__(self): 
        self.root=None 
 
    def insert(self,t): 
        '''inserts a new element into the tree''' 
        if self.root is None: 
            self.root = Node(t) 
        else: 
            self._do_insert(self.root,t) 
 
    def _do_insert(self,parent,t): 
        if t > parent.key: 
            if parent.left is None: 
                parent.left = Node(t) 
            else: 
                self._do_insert(parent.left,t) 
        elif t < parent.key: 
            if parent.right is None: 
                parent.right = Node(t) 
            else: 
                self._do_insert(parent.right,t) 
        else: 
            # raise a KeyError or something appropriate? 
            pass 

我有一个数字列表([2,4,6,3,190,1,56 等等]),通过它构造这个 BST。

现在我想找到创建的 BST 的高度。我该怎么做?

编辑

根据提供的解决方案,我尝试了这个:-

def create_bst(values): 
 
    '''Creates a BST and returns the BST created object''' 
    BSTobj = BST() 
 
    for i in values: 
        BSTobj.insert(i) 
 
    return BSTobj 
 
 
def height_of_BST(bst): 
 
    '''Returns the height of the BST created''' 
    if bst == None: return 0 
    else: return 1 + max(height_of_BST(bst.left), height_of_BST(bst.right)) 
 
 
print height_of_BST(create_bst(unique_values)) 

它不起作用。它弹出一个错误说 BST instance has no attribute 'left'

请您参考如下方法:

非空二叉搜索树的高度是 1 + 其最高子树的高度,或者如果它没有子树则仅为 1。这直接转化为递归算法。在伪代码中:

def height(bst): 
    if isempty(bst): 
        return 0 
    else: 
        return 1 + max(height(bst.left), height(bst.right))