Python实现深度遍历和广度遍历的方法

yipeiwu_com5年前Python基础

深度遍历:

原则:从上到下,从左到右

逻辑(本质用递归):

1)、找根节点

2)、找根节点的左边

3)、找根节点的右边

class Node(object):
 def __init__(self, item=None, left=None, right=None):
  self.item = item
  self.left = left
  self.right = right
 
 
d = Node("D")
e = Node("E")
b = Node("B", d, e)
f = Node("F")
g = Node("G")
c = Node("C", f, g)
a = Node("A", b, c)
 
 
result = []
 
 
def deep_search(root):
 # 深度遍历 核心:递归
 result.append(root.item)
 if root.left:
  deep_search(root.left)
 if root.right:
  deep_search(root.right)
 return "-->".join(result)
 
 
print deep_search(a)

广度遍历:

核心:队列+递归

def wide_search(root, result=[]):
 
 if not result:
  result.append(root.item)
 if root.left:
  result.append(root.left.item)
 if root.right:
  result.append(root.right.item)
 if root.left:
  wide_search(root.left)
 if root.right:
  wide_search(root.right)
 return "-->".join(result)
 
 
print wide_search(a)

以上这篇Python实现深度遍历和广度遍历的方法就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持【听图阁-专注于Python设计】。

相关文章

Python程序包的构建和发布过程示例详解

关于我 编程界的一名小程序猿,目前在一个创业团队任team lead,技术栈涉及Android、Python、Java和Go,这个也是我们团队的主要技术栈。 联系:hylinux1024...

python回调函数的使用方法

有两种类型的回调函数:复制代码 代码如下:blocking callbacks (also known as synchronous callbacks or just callback...

python计算圆周长、面积、球体体积并画出圆

python计算圆周长、面积、球体体积并画出圆

输入半径,计算圆的周长、面积、球体体积,并画出这个圆。拖动条、输入框和图像控件的数据保持一致! Fedora下测试通过 复制代码 代码如下:#https://github.com/Rob...

python实现字符串加密 生成唯一固定长度字符串

背景 有时候爬虫爬过的url需要进行指纹核对,比如Scrapy就是进行指纹核对,如果是指纹重复则不再爬取。当然在入库的时候我还是需要做一次核对,否则如果爬虫有漏掉,进入数据库就不合适了。...

利用python读取YUV文件 转RGB 8bit/10bit通用

注:本文所指的YUV均为YUV420中的I420格式(最常见的一种),其他格式不能用以下的代码。 位深为8bit时,每个像素占用1字节,对应文件指针的fp.read(1); 位深为10b...