偷闲,写了个初级二叉树排序

二叉树是计算机算法中普遍采用的数据结构。在所有排序算法中具有高效率的二叉树排序就是基于此结构。我抽空用新学的Python写了一个试试:

class node:
	left = None
	right = None
	value = 0

	def __init__(self, v):
		self.value = v

	def walk(self):
		r = []
		if self.left:
			r.extend(self.left.walk())
		r.append(self.value)
		if self.right:
			r.extend(self.right.walk())
		return r

	def insert(self, n):
		if self.value < n:
			if self.right:
				self.right.insert(n)
			else:
				self.right = node(n)
		else:
			if self.left:
				self.left.insert(n)
			else:
				self.left = node(n)

if __name__ == '__main__':
    s = [21,545,65,33,1,2324,232,42]
    p = node(s[0])
    for i in s[1:]:
	    p.insert(i)
    print p.walk()

运行结果

python bi-tree.py
[1, 21, 33, 42, 65, 232, 545, 2324]

结论:一次编写,基本正确。python很合我的路子啊。

BTW 用<pre>贴python code很正点:)

2 Replies to “偷闲,写了个初级二叉树排序”

  1. 站长好,希望能和贵站交换友情链接,贵站链接已经做好,在www.pianyi.cc首页的左下方,希望站长看到后能加上我们,我们的链接文字是:凡客诚品 链接网址:http://www.pianyi.cc/category/vancl
    谢谢!

Leave a Reply

Your email address will not be published. Required fields are marked *