python-二叉树:前、中、后、层序遍历
概要
本文只实现了二叉树基本的几种遍历,增、删、改、查,预计明天写完,后面的功能也尽量完善
定义Node数据结构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引用
相关推荐
sunjunior 2020-04-08
ipqtjmqj 2020-02-14
choupiaoyi 2020-02-01
Sophiego 2019-05-18
WindChaser 2019-06-21
Masimaro 2017-04-13
zhglinux 2018-07-27
龙源潇俊 2018-05-08
python的学习之路 2018-05-25
梦呓bolg 2017-12-12
yhguo00 2017-11-24
tansuo 2015-08-30
LeonTom 2017-06-02
electricperi 2015-02-15
大数据分析BDA 2014-08-02
云华00 2013-11-10
guyuanxiang 2014-04-29
妖怪哪里跑 2019-02-21
BitTigerio 2018-03-30