tinyxml2遍历所有节点_Python实现二叉树的遍历

3caf342f438202c303d9823e51191825.png

Outline:

  1. 二叉树概念
  2. 二叉树遍历(前序、中序、后序、宽度优先遍历)的迭代实现和递归实现;
  3. 二叉树的深度,二叉树到leaf的所有路径。

树(Tree)

是一种抽象数据类型(ADT),是由n(n>=0)个有限节点来模拟的一个具有树状结构性质的数据集合。

二叉树 Binary Tree

  • 至少有一个节点(根节点)
  • 每个节点最多有2棵子树(左右子树)(即每个节点的度小于3)
  • 左子树和右子树是有顺序的,次序不能任意颠倒。
  • 即使树中某节点只有一棵子树,也要区分它是左子树还是右子树。

Python定义二叉树类:

Class 

二叉树分类:

  • 满二叉树
  • 完全二叉树
  • 二叉查找树(Binary Search Tree - BST

二叉查找树

root node的值(5),大于其left subtree中任意一个节点的值,小于其right subtree中任意一节点的值。

【说人话】:以root节点为界,小于root节点的值保存在left节点,大于root节点的值保存在right节点。

ff94dc3992f65f3b8da08701bb5fb763.png
  • 任意节点的左、右子树也分别为二叉查找树;
  • 没有键值相等的节点

A binary search tree (BST) is a form of rooted binary tree.

Each node within a binary tree has an associated payload and references to the root node of any right or left subtrees at that point.

Any payload contained within any left subtree must be less than the value of the payload of node N and, conversely, that any payload contained within any right subtree must exceed the value of the payload of node N.


二叉树遍历

二叉树的遍历:

  • 深度优先(DFS: Depth-First Search)
  • 宽度优先(BFS: Breadth-First Search)

其中深度优先遍历又分为:

  • 前序遍历:-左-右
  • 中序遍历:左--右
  • 后序遍历:左-右-

前序遍历root-left-right: 5-3-2-4-7-6

递归

def 

中序遍历:left-root-right : 2-3-4-5-7-6

递归

def 

后序遍历left-right-root: 2-4-3-6-7-5

递归

def 

宽度优先遍历(BFS):自顶向下: 5-3-7-2-4-6

迭代

def 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值