最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

Python實(shí)現(xiàn)深度遍歷和廣度遍歷的方法

 更新時(shí)間:2019年01月22日 09:27:57   作者:納爾遜皮卡丘  
今天小編就為大家分享一篇Python實(shí)現(xiàn)深度遍歷和廣度遍歷的方法,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。一起跟隨小編過(guò)來(lái)看看吧

深度遍歷:

原則:從上到下,從左到右

邏輯(本質(zhì)用遞歸):

1)、找根節(jié)點(diǎn)

2)、找根節(jié)點(diǎn)的左邊

3)、找根節(jié)點(diǎn)的右邊

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)

廣度遍歷:

核心:隊(duì)列+遞歸

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實(shí)現(xiàn)深度遍歷和廣度遍歷的方法就是小編分享給大家的全部?jī)?nèi)容了,希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。

相關(guān)文章

最新評(píng)論

湘阴县| 商城县| 微山县| 宝山区| 鸡东县| 陇西县| 西华县| 陆川县| 青阳县| 银川市| 丹江口市| 余庆县| 游戏| 象州县| 油尖旺区| 新平| 盖州市| 承德市| 绥化市| 昌乐县| 府谷县| 建阳市| 南汇区| 屯昌县| 和平区| 图们市| 吉木萨尔县| 抚顺市| 肥西县| 肥西县| 介休市| 云梦县| 咸丰县| 马尔康县| 香港 | 玉树县| 会同县| 平阳县| 宜川县| 泰安市| 扶沟县|