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 捕获shell脚本的输出结果实例

import subprocess output =Popen(["mycmd","myarg"], stdout=PIPE).communicate()[0] import subp...

django admin 自定义替换change页面模板的方法

django admin 自定义替换change页面模板的方法

举个简单的例子:(此仅限于修改change_form页面) 原来的时候,change_form_list是包含这些按钮的: 因为此页面继承了 {% extends 'admin/c...

利用Python实现简单的相似图片搜索的教程

利用Python实现简单的相似图片搜索的教程

大概五年前吧,我那时还在为一家约会网站做开发工作。他们是早期创业公司,但他们也开始拥有了一些稳定用户量。不像其他约会网站,这家公司向来以洁身自好为主要市场形象。它不是一个供你鬼混的网站—...

Python最基本的输入输出详解

输出 用print加上字符串,就可以向屏幕上输出指定的文字。比如输出'hello, world',用代码实现如下: >>> print 'hello, world'...

Python制作词云的方法

Python制作词云的方法

需求: 看到朋友圈有人发词云照片,感觉自己也可以玩一玩,于是乎借助wordcloud实现功能。 环境: MacOS 10.12 +Python 2.7 +Wordcloud Windo...