1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| class Node:
def __init__(self,data,next):
self.data = data
self.next = next
L = Node('L',None)
K = Node('K',None)
F = Node('F',None)
E = Node('E',[K,L])
B = Node('B',[E,F])
G = Node('G',None)
C = Node('C',[G])
M = Node('M',None)
H = Node('H',[M])
I = Node('I',None)
J = Node('J',None)
D = Node('D',[H,I,J])
A = Node('A',[B,C,D])
|
### 2. 二叉树:每个节点最多只有两个的树。
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
| # 定义一个节点,这里定义的节点只有左子树和有右子树,如果需要还可以加一个指向父节点的指针,称为三叉链表
class Node:
def __init__(self,data):
self.left = None
self.data = data
self.right = None
def setLeft(self,left):
self.left = left
return self
def setRight(self,right):
self.right = right
return self
'''
来模拟这棵树的存储
1
/ \
2 3
/
4
'''
def createTree():
n4 = Node(4)
n2 = Node(2).setLeft(n4)
n3 =Node(3)
n1 = Node(1).setLeft(n2).setRight(n3)
return n1
t = createTree()
print(t.data)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| t = createTree()
# 先序遍历 递归版本
def printTree(tree,l):
if tree:
l.append(tree.data)
printTree(tree.left,l)
printTree(tree.right,l)
return l
l = printTree(t,[])
print(l)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| # 先序遍历,非递归版本,依靠栈来实现
def printTree1(tree):
l = []
stack = [tree] # 根节点
while stack: # 当栈为空时,退出循环
p = stack.pop() # 弹出节点
while p:
l.append(p.data) # 把节点中的值添加到列表中,打印
if p.right: # 如果节点有右子树,压入栈
stack.append(p.right)
p = p.left # 节点一直指向左子树
return l
print(printTree1(t))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
| t = createTree()
# 中序序遍历 递归版本
def printTree(tree,l):
if tree:
printTree(tree.left, l)
l.append(tree.data)
printTree(tree.right, l)
return l
l = printTree(t,[])
print(l)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| # 中序遍历,非递归版本,依靠栈来实现
def printTree1(tree):
l = []
p = tree
stack = [] # 栈
while stack or p: # 当栈为空时,退出循环
if p:
stack.append(p)
p = p.left
else:
p = stack.pop()
l.append(p.data)
p = p.right
return l
print(printTree1(t))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
| t = createTree()
# 后序序遍历 递归版本
def printTree(tree,l):
if tree:
printTree(tree.right, l)
l.append(tree.data)
printTree(tree.left, l)
return l
l = printTree(t,[])
print(l)
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
| # 后序遍历,非递归版本,依靠栈来实现
def printTree1(tree):
l = []
p = tree
stack = [] # 栈
while stack or p: # 当栈为空时,退出循环
if p: # 入栈,同时继续指向右子树
stack.append(p)
p = p.right
else: # 出栈,打印,节点指向左子树
p = stack.pop()
l.append(p.data)
p = p.left
return l
print(printTree1(t))
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
| # 层序遍历,利用队列的特性
def printTree(tree):
t = tree
l = []
queue = []
queue.append(t) # 先将跟节点入队
while queue: # 队列不为空
node = queue.pop(0)
if node.left:
queue.append(node.left)
if node.right:
queue.append(node.right)
l.append(node.data)
return l
print(printTree(t))
|