python二叉树深度遍历_Python实现二叉树的遍历

Outline:二叉树概念

二叉树遍历(前序、中序、后序、宽度优先遍历)的迭代实现和递归实现;

二叉树的深度,二叉树到leaf的所有路径。

树(Tree)

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

二叉树 Binary Tree至少有一个节点(根节点)

每个节点最多有2棵子树(左右子树)(即每个节点的度小于3)

左子树和右子树是有顺序的,次序不能任意颠倒。

即使树中某节点只有一棵子树,也要区分它是左子树还是右子树。

Python定义二叉树类:

Class TreeNode:

def __init__(self,x,left_x=None, right_x=None):

self.val=x

self.left=left_x

self.right=right_x

二叉树分类:满二叉树

完全二叉树

二叉查找树(Binary Search Tree - BST)

二叉查找树

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

【说人话】:以root节点为界,小于root节点的值保存在left节点,大于root节点的值保存在right节点。任意节点的左、右子树也分别为二叉查找树;

没有键值相等的节点

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 preOrder(root):

if not root:

return

print(root.val)

preOrder(root.left)

preOrder(root.right)

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

递归

def inorder(root):

if not root:

return # ???

inorder(root.left)

print(root.val)

inorder(root.right)

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

递归

def postOrder(root):

if not root:

return

postOrder(root.left)

postOrder(root.right)

print(root.val)

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

迭代

def BFS(root):

queue = [root]

while queue:

n = len(queue)

for i in range(n):

q = queue.pop(0)

if q:

print(q.val)

queue.append(q.left if q.left else None)

queue.append(q.right if q.right else None)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值