用python实现搜索树,如何在Python中实现二进制搜索树?

This is what I've got so far but it is not working:

class Node:

rChild,lChild,data = None,None,None

def __init__(self,key):

self.rChild = None

self.lChild = None

self.data = key

class Tree:

root,size = None,0

def __init__(self):

self.root = None

self.size = 0

def insert(self,node,someNumber):

if node is None:

node = Node(someNumber)

else:

if node.data > someNumber:

self.insert(node.rchild,someNumber)

else:

self.insert(node.rchild, someNumber)

return

def main():

t = Tree()

t.root = Node(4)

t.root.rchild = Node(5)

print t.root.data #this works

print t.root.rchild.data #this works too

t = Tree()

t.insert(t.root,4)

t.insert(t.root,5)

print t.root.data #this fails

print t.root.rchild.data #this fails too

if __name__ == '__main__':

main()

解决方案

Here is a quick example of a binary insert:

class Node:

def __init__(self, val):

self.l_child = None

self.r_child = None

self.data = val

def binary_insert(root, node):

if root is None:

root = node

else:

if root.data > node.data:

if root.l_child is None:

root.l_child = node

else:

binary_insert(root.l_child, node)

else:

if root.r_child is None:

root.r_child = node

else:

binary_insert(root.r_child, node)

def in_order_print(root):

if not root:

return

in_order_print(root.l_child)

print root.data

in_order_print(root.r_child)

def pre_order_print(root):

if not root:

return

print root.data

pre_order_print(root.l_child)

pre_order_print(root.r_child)

r = Node(3)

binary_insert(r, Node(7))

binary_insert(r, Node(1))

binary_insert(r, Node(5))

3

/ \

1 7

/

5

print "in order:"

in_order_print(r)

print "pre order"

pre_order_print(r)

in order:

1

3

5

7

pre order

3

1

7

5

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值