最新国产好看的视频,伊人天堂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)論

梁山县| 宁安市| 宣城市| 密山市| 宁晋县| 石台县| 汝南县| 资溪县| 阳西县| 濮阳市| 永州市| 河源市| 芒康县| 浪卡子县| 婺源县| 广丰县| 邢台县| 怀集县| 济阳县| 桃园县| 陆河县| 攀枝花市| 凤庆县| 保康县| 达孜县| 克山县| 宾阳县| 吴川市| 枣强县| 新竹市| 营口市| 桐庐县| 连江县| 巴东县| 铅山县| 福建省| 岳阳县| 常德市| 会昌县| 扬州市| 嘉义县|