Skip to content

Commit 1c44932

Browse files
author
Your Name
committed
Tree
1 parent f03c15f commit 1c44932

File tree

1 file changed

+75
-0
lines changed
  • AlgorithmAndDataStructure/Basic

1 file changed

+75
-0
lines changed
+75
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,75 @@
1+
class Node(object):
2+
3+
def __init__(self, elem=-1, lchild=None, rchirld=None):
4+
self.elem = elem
5+
self.lchild = lchild
6+
self.rchirld = rchirld
7+
8+
9+
class Tree(object):
10+
11+
def __init__(self, root=None):
12+
self.root = root
13+
14+
def add(self, elem):
15+
node = Node(elem)
16+
if self.root == None:
17+
self.root = node
18+
else:
19+
queue = []
20+
queue.append(self.root)
21+
"""cur = queue.pop(0)
22+
对已有的节点进行遍历"""
23+
while queue:
24+
cur = queue.pop(0)
25+
if cur.lchild == None:
26+
cur.lchild = node
27+
return
28+
elif cur.rchirld == None:
29+
cur.rchirld = node
30+
return
31+
else:
32+
queue.append(cur.lchild)
33+
queue.append(cur.rchirld)
34+
35+
36+
"""Depth First Search"""
37+
def preorder(self, root):
38+
"""递归实现先序遍历"""
39+
if root == None:
40+
return
41+
print root.elem
42+
self.preorder(root.lchild)
43+
self.preorder(root.rchirld)
44+
45+
def inorder(self, root):
46+
"""递归实现中序遍历"""
47+
if root == None:
48+
return
49+
self.inorder(root.lchild)
50+
print root.elem
51+
self.inorder(root.rchirld)
52+
53+
def postorder(self, root):
54+
if root == None:
55+
return
56+
self.postorder(root.lchild)
57+
self.postorder(root.rchirld)
58+
print root.elem
59+
60+
"""Breadth First Search"""
61+
def breadth_travel(self, root):
62+
"""利用队列实现树的层次遍历"""
63+
if root == None:
64+
return
65+
queue = []
66+
queue.append(root)
67+
while queue:
68+
node = queue.pop(0)
69+
print node.elem
70+
if node.lchild != None:
71+
queue.append(node.lchild)
72+
if node.rchirld != None:
73+
queue.append(node.rchirld)
74+
75+

0 commit comments

Comments
 (0)