二叉树的应用在开发中会有很多的应用,比如:数据库的设计,程序功能的实现等待,所有掌握二叉树的构建是很有必要的
构建树
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, data):
node = Node(data)
if self.root == None:
self.root = node
return
queue = [self.root]
while queue:
cur = queue.pop(0)
if cur.left == None:
cur.left = node
return
else:
queue.append(cur.left)
if cur.right == None:
cur.right = node
return
else:
queue.append(cur.right)
if __name__ == '__main__':
tree = Tree()
for i in range(10):
tree.add(i)
广度优先遍历
# 广度优先遍历
def scope_travel(self):
if self.root is None:
return
queue = [self.root]
while queue:
cur = queue.pop(0)
print(cur.data, end=' ')
if cur.left is not None:
queue.append(cur.left)
if cur.right is not None:
queue.append(cur.right)
深度优先遍历
先序遍历
# 先序遍历
def preorder_travel(self, node):
if node is None:
return
print(node.data, end=' ')
self.preorder_travel(node.left)
self.preorder_travel(node.right)
中序遍历
# 中序遍历
def inorder_travel(self, node):
if node is None:
return
self.inorder_travel(node.left)
print(node.data, end=' ')
self.inorder_travel(node.right)
后序遍历
# 后序遍历
def postorder_travel(self, node):
if node is None:
return
self.postorder_travel(node.left)
self.postorder_travel(node.right)
print(node.data, end=' ')
完整代码
class Node:
def __init__(self, data):
self.data = data
self.left = None
self.right = None
class Tree:
def __init__(self):
self.root = None
def add(self, data):
node = Node(data)
if self.root == None:
self.root = node
return
queue = [self.root]
while queue:
cur = queue.pop(0)
if cur.left is None:
cur.left = node
return
else:
queue.append(cur.left)
if cur.right is None:
cur.right = node
return
else:
queue.append(cur.right)
# 广度优先遍历
def scope_travel(self):
if self.root is None:
return
queue = [self.root]
while queue:
cur = queue.pop(0)
print(cur.data, end=' ')
if cur.left is not None:
queue.append(cur.left)
if cur.right is not None:
queue.append(cur.right)
# 先序遍历
def preorder_travel(self, node):
if node is None:
return
print(node.data, end=' ')
self.preorder_travel(node.left)
self.preorder_travel(node.right)
# 中序遍历
def inorder_travel(self, node):
if node is None:
return
self.inorder_travel(node.left)
print(node.data, end=' ')
self.inorder_travel(node.right)
# 后序遍历
def postorder_travel(self, node):
if node is None:
return
self.postorder_travel(node.left)
self.postorder_travel(node.right)
print(node.data, end=' ')
if __name__ == '__main__':
tree = Tree()
for i in range(10):
tree.add(i)
# 广度优先
print('广度优先')
tree.scope_travel()
print()
# 深度优先
# 先序遍历
print('深度优先')
print('先序遍历')
tree.preorder_travel(tree.root)
print()
# 中序遍历
print('中序遍历')
tree.inorder_travel(tree.root)
print()
# 后序遍历
print('后序遍历')
tree.postorder_travel(tree.root)