基于 Python 的数据结构与算法分析学习记录(6-7)—— 树的遍历
来源:互联网 发布:工业企业利润数据 编辑:程序博客网 时间:2024/05/20 07:35
前序 在前序遍历中,我们首先访问根节点,然后递归地做左侧子树的前序遍历,随后是右侧子树的递归前序遍历。
中序 在一个中序遍历中,我们递归地对左子树进行一次遍历,访问根节点,最后递归遍历右子树。
后序 在后序遍历中,我们递归地对左子树和右子树进行后序遍历,然后访问根节点。
编写树遍历的代码惊人地优雅,主要是因为遍历是递归写的。
# -*- 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 functiondef 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)
0 0
- 基于 Python 的数据结构与算法分析学习记录(6-7)—— 树的遍历
- 基于 Python 的数据结构与算法分析学习记录(6-6)—— 分析树
- 基于 Python 的数据结构与算法分析学习记录(6-11)—— 二叉查找树与操作
- 基于 Python 的数据结构与算法分析学习记录(6-5)——树的节点表示
- 基于 Python 的数据结构与算法分析学习记录(6-8)—— 基于二叉堆的优先队列
- 基于 Python 的数据结构与算法分析学习记录(6-9)—— 二叉堆操作
- 基于 Python 的数据结构与算法分析学习记录(6-10)—— 二叉堆实现
- Python数据结构与算法分析学习记录(1)——基于Problem Solving with Algorithms and Data Structures using Python的学习
- Python数据结构与算法分析学习记录(2)——基于Problem Solving with Algorithms and Data Structures using Python的学习
- 数据结构与算法学习记录--二叉树的创建,递归遍历,非递归遍历的实现
- python数据结构与算法 39 树的遍历
- 数据结构学习记录-二叉树的遍历
- 数据结构—基于深度优先遍历算法的应用
- 数据结构—基于广度优先遍历算法的应用
- 基于Python的二叉树遍历算法
- 【算法】数据结构与算法分析学习笔记——各类二叉查找树的吐血整理
- 【数据结构与算法】二叉树的遍历(递归遍历、非递归遍历、层序遍历)
- Java学习札记(一)——基于数据结构与算法分析
- 接口与抽象类
- Volly的简单封装
- SpannableStringBuilder 同时设置setclickspan 和 ForegroundColorSpan出现问题
- 数据结构 第五章 数和二叉树
- 数据科学家的修行之路---基本功
- 基于 Python 的数据结构与算法分析学习记录(6-7)—— 树的遍历
- [Leetcode] #334 Increasing Triplet Subsequence
- 【C语言常识】mdk:Inline assembler rules for compiler keywords __asm and asm
- apache kafka系列之在zookeeper中存储结构
- SQL 视图 局部变量 全局变量 条件语句 事务 触发器
- Uncaught TypeError: Cannot read property 'trigger' of undefined(zepto.js)
- Ubuntu里shell和命令执行结果不同(Bash和sh区别)
- asp.net中的cookie
- Java数组全排列