基于 Python 的数据结构与算法分析学习记录(6-7)—— 树的遍历
2017-05-08 10:37
627 查看
前序 在前序遍历中,我们首先访问根节点,然后递归地做左侧子树的前序遍历,随后是右侧子树的递归前序遍历。
中序 在一个中序遍历中,我们递归地对左子树进行一次遍历,访问根节点,最后递归遍历右子树。
后序 在后序遍历中,我们递归地对左子树和右子树进行后序遍历,然后访问根节点。
编写树遍历的代码惊人地优雅,主要是因为遍历是递归写的。
中序 在一个中序遍历中,我们递归地对左子树进行一次遍历,访问根节点,最后递归遍历右子树。
后序 在后序遍历中,我们递归地对左子树和右子树进行后序遍历,然后访问根节点。
编写树遍历的代码惊人地优雅,主要是因为遍历是递归写的。
# -*- coding:utf-8 -*- class BinaryTree(object): def __init__(self, rootObj): self.key = rootObj self.leftChild = None self.rightChild = None def insertLeft(self, newNode): if self.leftChild is None: self.leftChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.leftChild = self.leftChild self.leftChild = t def insertRight(self, newNode): if self.rightChild is None: self.rightChild = BinaryTree(newNode) else: t = BinaryTree(newNode) t.rightChild = self.rightChild self.rightChild = t def getLeftChild(self): return self.leftChild def getRightChild(self): return self.rightChild def setRootVal(self, obj): self.key = obj def getRootVal(self): return self.key # as an external function def preorder(tree): if tree: print(tree.getRootVal()) preorder(tree.getLeftChild()) preorder(tree.getRightChild()) def postorder(tree): if tree: postorder(tree.getLeftChild()) postorder(tree.getRightChild()) print(tree.getRootVal()) def inorder(tree): if tree: inorder(tree.getLeftChild()) print(tree.getRootVal()) inorder(tree.getRightChild()) r = BinaryTree('a') r.insertLeft('b') r.getLeftChild().insertRight('d') r.insertRight('c') r.getRightChild().insertLeft('e') r.getRightChild().insertRight('f') print('先序遍历:') preorder(r) print('中序遍历:') inorder(r) print('后序遍历:') postorder(r)
相关文章推荐
- 基于 Python 的数据结构与算法分析学习记录(6-6)—— 分析树
- 基于 Python 的数据结构与算法分析学习记录(6-10)—— 二叉堆实现
- 基于 Python 的数据结构与算法分析学习记录(6-5)——树的节点表示
- 基于 Python 的数据结构与算法分析学习记录(6-11)—— 二叉查找树与操作
- 基于 Python 的数据结构与算法分析学习记录(6-8)—— 基于二叉堆的优先队列
- Python数据结构与算法分析学习记录(1)——基于Problem Solving with Algorithms and Data Structures using Python的学习
- Python数据结构与算法分析学习记录(2)——基于Problem Solving with Algorithms and Data Structures using Python的学习
- 基于 Python 的数据结构与算法分析学习记录(6-9)—— 二叉堆操作
- 基于Problem Solving with Algorithms and Data Structures using Python的学习记录(5)——Sorting
- 基于Problem Solving with Algorithms and Data Structures using Python的学习记录(3)——Basic Data Structures
- python 学习记录(11)-文件处理/读取文件/文件写入内容/文件删除/文件复制/文件重命名/后缀名/内容查找与替换/文件比较/ 配置文件访问/目录创建与删除/遍历目录/定向输出
- 基于Problem Solving with Algorithms and Data Structures using Python的学习记录(6-1)——Tree
- python爬虫【记录】BeautifulSoup 的用法遍历学习
- python学习记录第五篇--遍历目录
- python+字典的遍历与排序以及后续的学习记录
- 既然决定学习python就开始记录一些问题吧
- 神经网络与深度学习 使用Python实现基于梯度下降算法的神经网络和自制仿MNIST数据集的手写数字分类可视化程序 web版本
- 深度学习(DL)与卷积神经网络(CNN)学习随笔-05-基于Python的LeNet之CNN
- 基于Beautiful Soup 4.2.0文档的学习记录(2)——CSS选择器
- Python学习记录(一)