Python二进制搜索树高度函数不起作用

时间:2016-02-10 17:22:12

标签: python python-3.x binary-search-tree

我一直在尝试递归方法但是已经停留太久了。我无法判断我的BST代码是错误的还是我的递归。

无论我在树上放了多少元素,我仍然从高度函数中得到值2.

class Treenode:
    def __init__(self, value = None, rchild = None, lchild = None):
        self.value = value
        self.rchild = rchild
        self.lchild = lchild

class bin_tree:
   def __init__(self):
        self.root = None

   def put(self, x):
       if self.root is None:
           self.root = Treenode(x)
           return True
       if self.exists(x) == True:
           return False

       p = self.root

       while True:
           if x < p.value:
              if p.lchild is None:
                 p.lchild = Treenode(x)
                 return True
               else:
                   p = p.lchild
           elif x > p.value:
               if p.rchild is None:
                  p.rchild = Treenode(x)
                  return True
               else:
                  p = p.rchild
                  return

   def exists(self, x):
      p = self.root
         while True and p != None:
            if p.value == x:
               return True
            elif p.value > x and p.lchild != None:
               p = p.lchild
            elif p.value < x and p.rchild != None:
               p = p.rchild
            else:
               return False

   def isempty(self):
      return self.root == None

   def height(self):
      def gh(enrot):
         if enrot == None:
            return 0
         else:
            return 1 + max(gh(enrot.lchild), gh(enrot.rchild))
      return gh(self.root)

示例代码:

from Bintree import *

p = bin_tree()

x = input()

for word in x.split():
    p.put(word)

a = input()

if p.exists(a) is True:
    print('Exists!')
else:
    print('Does not exist!')

print(p.isempty())

print(p.height())

1 个答案:

答案 0 :(得分:1)

height方法很好。在put方法中,在没有实际添加元素的情况下停止,因此高度实际上不会超过2:

   def put(self, x):
       ...
       while True:
           if x < p.value:
              ...
           elif x > p.value:
               if p.rchild is None:
                  ...
               else:
                  p = p.rchild
                  return
#                 ^^^^^^ This shouldn't be here.