# python-二叉树：前、中、后、层序遍历

Geekrun

``````class Node(object):
def __init__(self, data):
self.data = data
self.lft = None #左节点
self.rgt = None #右节点
``````

## 先序遍历

``````class BTree(object):
def __init__(self):
self._root = None
self._size = 0

def preOrder(self):
'''
先遍历顺序：
1，根节点
2，遍历左子树
3，遍历右子树
'''
btree = []

def recurse(node):
if node != None:
btree.append(node.data)
recurse(node.lft)
recurse(node.rgt)

recurse(self._root)
return btree``````

``````class BTree(object):
def __init__(self):
self._root = None
self._size = 0

# 中序遍历
def inOrder(self):
'''
中序遍历顺序：
1，遍历左子树
2，根节点
3，遍历右子树
'''
btree = []

def recurse(node):
if node != None:
recurse(node.lft)
btree.append(node.data)
recurse(node.rgt)

recurse(self._root)
return btree``````

``````class BTree(object):
def __init__(self):
self._root = None
self._size = 0

# 后序遍历
def postOrder(self):
'''
后序遍历顺序：
1，遍历左子树
2，遍历右子树
3，根节点
'''
btree = []

def recurse(node):
if node != None:
recurse(node.lft)
recurse(node.rgt)
btree.append(node.data)

recurse(self._root)
return btree``````

``````from  collections import deque

class BTree(object):
def __init__(self):
self._root = None
self._size = 0

# 层序遍历
def leverOrder(self):
q = deque()
q.append(self._root)
btree = []
while q:
#dque是一个双向队列，先进先出是popleft
node = q.popleft()
btree.append(node.data)
if node.lft:
q.append(node.lft)
if node.rgt:
q.append(node.rgt)
return btree``````

github 源码Btree源码

12 声望
1 粉丝
0 条评论