# Python实现二叉树的存储和遍历

```class Node(object):
""""树的节点类"""

def __init__(self, item):
self.item = item
# 记录左孩子
self.lChild = None
# 记录右孩子
self.rChild = None

class Tree(object):
"""树"""

def __init__(self):
self.__root = None

# 添加节点
node = Node(item)
# 判断是否为空
if self.__root is None:
self.__root = node
else:
# 以队列的方式变量树
queue = []
queue.append(self.__root)

while queue:
cur = queue.pop(0)

if cur.lChild is None:
cur.lChild = node
return
if cur.rChild is None:
cur.rChild = node
return
queue.append(cur.lChild)
queue.append(cur.rChild)

# 广度优先遍历，层次遍历
def breath_travel(self):
if self.__root is None:
return

# 以队列的方式进行遍历
queue = []
queue.append(self.__root)

while queue:
cur = queue.pop(0)
print(cur.item)

if cur.lChild is not None:
queue.append(cur.lChild)
if cur.rChild is not None:
queue.append(cur.rChild)

# 深度优先遍历
def depth_travel(self):
self.post_order(self.__root)

# 后序
def post_order(self, node):
if node is None:
return
self.post_order(node.lChild)
self.post_order(node.rChild)
print(node.item, end=" ")

# 中序
def in_order(self, node):
if node is None:
return
self.in_order(node.lChild)
print(node.item, end=" ")
self.in_order(node.rChild)

# 先序
def pre_order(self, node):
if node is None:
return
print(node.item, end=" ")
self.pre_order(node.lChild)
self.pre_order(node.rChild)

if __name__ == '__main__':
tree = Tree()