-
Notifications
You must be signed in to change notification settings - Fork 0
/
08-1树的类.py
45 lines (32 loc) · 977 Bytes
/
08-1树的类.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
# coding :utf-8
# 树是链表的扩充
class Node(object):
def __init__(self,item) :
self.elem = item
self.lchild = None # 左孩子
self.rchild = None # 又孩子
class Tree(object):
#二叉树
def __init__(self):
self,root = None # 跟节点
# 类似队列
def add(self,item):
node = Node(item)
queue = [self.root] # 初始化
if self.root is None:
self.root = node
return
while queue:
cur_node = queue.pop(0)
if cur_node.lchild is None:
cur_node.lchild = node
return
else:
queue.append(cur_node.lchild)
if cur_node.rchild is None:
cur_node.rchild = node
return
else:
queue.append(cur_node.rchild)
if __name__ == "__main__":
tree = Tree()