-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtree.py
75 lines (63 loc) · 1.43 KB
/
tree.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
class Node(object):
def __init__(self, elem=-1, lchild=None, rchirld=None):
self.elem = elem
self.lchild = lchild
self.rchirld = rchirld
class Tree(object):
def __init__(self, root=None):
self.root = root
def add(self, elem):
node = Node(elem)
if self.root == None:
self.root = node
else:
queue = []
queue.append(self.root)
"""cur = queue.pop(0)
对已有的节点进行遍历"""
while queue:
cur = queue.pop(0)
if cur.lchild == None:
cur.lchild = node
return
elif cur.rchirld == None:
cur.rchirld = node
return
else:
queue.append(cur.lchild)
queue.append(cur.rchirld)
"""Depth First Search"""
def preorder(self, root):
"""递归实现先序遍历"""
if root == None:
return
print root.elem
self.preorder(root.lchild)
self.preorder(root.rchirld)
def inorder(self, root):
"""递归实现中序遍历"""
if root == None:
return
self.inorder(root.lchild)
print root.elem
self.inorder(root.rchirld)
def postorder(self, root):
if root == None:
return
self.postorder(root.lchild)
self.postorder(root.rchirld)
print root.elem
"""Breadth First Search"""
def breadth_travel(self, root):
"""利用队列实现树的层次遍历"""
if root == None:
return
queue = []
queue.append(root)
while queue:
node = queue.pop(0)
print node.elem
if node.lchild != None:
queue.append(node.lchild)
if node.rchirld != None:
queue.append(node.rchirld)