二叉树:二叉树是每个结点最多有两个子树的树结构。通常子树被称作“左子树”和“右子树”
**
python代码实现如下:
- 二叉树的创建
- 二叉树的层次遍历
- 二叉树的先序遍历
- 二叉树的中序遍历
- 二叉树的后序遍历
#coding:utf-8
class Node:
def __init__(self, val=None, left=None, right=None):
self.val = val
self.left = left
self.right = right
class Tree:
def __init__(self, root=None):
self.root = root
def add(self, val):
"""
添加节点元素
:param val:
:return:
"""
node = Node(val)
if self.root is None:
self.root = node
return
queue = [self.root]
while queue:
cur = queue.pop(0)
if cur.left is not None:
queue.append(cur.left)
else:
cur.left = node
return
if cur.right is not None:
queue.append(cur.right)
else:
cur.right = node
return
def breadth_travel(self):
"""
层次遍历/广度优先
:param val:
:return:
"""
if self.root is None:
return
queue = [self.root]
while queue:
cur = queue.pop(0)
print(cur.val, end='')
if cur.left is not None:
queue.append(cur.left)
if cur.right is not None:
queue.append(cur.right)
def left_travel(self, root):
"""
前序遍历/深度优先
:param val:
:return:
"""
if root is None:
return
print(root.val, end='')
self.left_travel(root.left)
self.left_travel(root.right)
def mid_travel(self, root):
"""
中序遍历/深度优先
:param val:
:return:
"""
if root is None:
return
self.mid_travel(root.left)
print(root.val, end='')
self.mid_travel(root.right)
def right_travel(self, root):
"""
后序遍历/深度优先
:param val:
:return:
"""
if root is None:
return
self.right_travel(root.left)
self.right_travel(root.right)
print(root.val, end='')
if __name__ == '__main__':
tree = Tree()
tree.add(0)
tree.add(1)
tree.add(2)
tree.add(3)
tree.add(4)
tree.add(5)
tree.add(6)
tree.add(7)
tree.add(8)
tree.add(9)
tree.breadth_travel()
tree.left_travel(tree.root)
tree.right_travel(tree.root)
tree.mid_travel(tree.root)