日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程语言 > python >内容正文

python

二叉树层次遍历python_根据二叉树层序遍历顺序(数组),将其转换为二叉树(Python)...

發布時間:2025/3/15 python 21 豆豆
生活随笔 收集整理的這篇文章主要介紹了 二叉树层次遍历python_根据二叉树层序遍历顺序(数组),将其转换为二叉树(Python)... 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

1.創建二叉樹結點和值

class Node:

def __init__(self, value):

self.value = value

self.left = None

self.right = None

2.構造二叉樹

alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]

def creatTree(alist):

li = []

for a in alist: # 創建結點

node = Node(a)

li.append(node)

parentNum = len(li) // 2 - 1

for i in range(parentNum+1):

leftIndex = 2 * i + 1

rightIndex = 2 * i + 2

li[i].left = li[leftIndex]

if rightIndex < len(li): # 判斷是否有右結點, 防止數組越界

li[i].right = li[rightIndex]

return li[0]

備注:

# 依據索引值找到父節點: lastParent = (index -1 ) // 2

# 依據數組的長度找到最后一個父節點: lastParent = len(li) // 2 - 1

3.中序遍歷所有的結點

def in_order(root):

if not root:

return

print(root.value)

in_order(root.left)

in_order(root.right)

in_order(creatTree(alist))

4.層次遍歷所有的結點

# 層次遍歷所有的結點

def BFS(root):

queue, result = [root], []

while queue:

node = queue.pop(0)

result.append(node.value)

if node.left:

queue.append(node.left)

if node.right:

queue.append(node.right)

return result

print(BFS(creatTree(alist)))

希望幫助到有需要的朋友們,方便創建自己的二叉樹-----------------------

同理,

依據一個數組創建一個鏈表:

# 依據數組創建一個鏈表

alist1 = [1, 2, 3, 4, 5, 6, 7, 8, 9]

class LinkNode:

def __init__(self, value):

self.value = value

self.next = None

def creatLink(alist):

li = [LinkNode(a) for a in alist]

for i in range(len(li)-1):

li[i].next = li[i+1]

return li[0]

def showLink(root):

result = []

while root:

result.append(root.value)

root = root.next

return result

print(showLink(creatLink(alist1)))

總結

以上是生活随笔為你收集整理的二叉树层次遍历python_根据二叉树层序遍历顺序(数组),将其转换为二叉树(Python)...的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。