Python中的二叉树查找算法模块使用指南

2019-10-06 12:49:04王冬梅

- 输出字符串模样,注意仅仅是输出的模样罢了: .__repr__()

看例子:

>>> btree
  BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'})
  >>> btree.__repr__()
  "BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'})"

- 清空树中的所有数据 :.clear(),O(log(n))

看例子:

>>> bother  
 BinaryTree({3: 'http://blog.csdn.net/qiwsir', 7: 'qiwsir'})
 >>> bother.clear()
 >>> bother
 BinaryTree({})
 >>> bool(bother)
 False

- 浅拷贝: .copy(),官方文档上说是浅拷贝,但是我做了操作实现,是下面所示,还不是很理解其“浅”的含义。O(n*log(n))

看例子:

>>> btree
 BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'})
 >>> ctree = btree.copy()
 >>> ctree
 BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'})

 >>> btree.__setitem__("github","qiwsir") #增加btree的数据
 >>> btree
 BinaryTree({2: 'phone', 7: 'computer', 9: 'scree', 'github': 'qiwsir'})
 >>> ctree
 BinaryTree({2: 'phone', 7: 'computer', 9: 'scree'}) #这是不是在说明属于深拷贝呢?
 
 >>> ctree.__delitem__(7) #删除ctree的一个数据
 >>> ctree
 BinaryTree({2: 'phone', 9: 'scree'})
 >>> btree
 BinaryTree({2: 'phone', 7: 'computer', 9: 'scree', 'github': 'qiwsir'})

  

- 移除树中的一个数据: .discard(key),这个功能与.__delitem__(key)类似.两者都不反悔值。O(log(n))

看例子:

>>> ctree
 BinaryTree({2: 'phone', 9: 'scree'})
 >>> ctree.discard(2) #删除后,不返回值,或者返回None
 >>> ctree
 BinaryTree({9: 'scree'})
 >>> ctree.discard(2) #如果删除的key不存在,也返回None
 >>> ctree.discard(3)
 >>> ctree.__delitem__(3) #但是,.__delitem__(key)则不同,如果key不存在,会报错。
 Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/usr/local/lib/python2.7/site-packages/bintrees/abctree.py", line 264, in __delitem__
  self.remove(key)
  File "/usr/local/lib/python2.7/site-packages/bintrees/bintree.py", line 124, in remove
  raise KeyError(str(key))
  KeyError: '3'

- 根据key查找,并返回或返回备用值: .get(key[,d])。如果key在树中存在,则返回value,否则如果有d,则返回d值。O(log(n))

看例子:

>>> btree
 BinaryTree({2: 'phone', 7: 'computer', 9: 'scree', 'github': 'qiwsir'})
 >>> btree.get(2,"algorithm")
 'phone'
 >>> btree.get("python","algorithm") #没有key='python'的值,返回'algorithm'
 'algorithm'
 >>> btree.get("python") #如果不指定第二个参数,若查不到,则返回None
 >>>

- 判断树是否为空: is_empty().根据树数据的长度,如果数据长度为0,则为空。O(1)