二叉树层次遍历python_根据二叉树层序遍历顺序(数组),将其转换为二叉树(Python)...
1.創(chuàng)建二叉樹結(jié)點(diǎn)和值
class Node:
def __init__(self, value):
self.value = value
self.left = None
self.right = None
2.構(gòu)造二叉樹
alist = [1, 2, 3, 4, 5, 6, 7, 8, 9]
def creatTree(alist):
li = []
for a in alist: # 創(chuàng)建結(jié)點(diǎn)
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): # 判斷是否有右結(jié)點(diǎn), 防止數(shù)組越界
li[i].right = li[rightIndex]
return li[0]
備注:
# 依據(jù)索引值找到父節(jié)點(diǎn): lastParent = (index -1 ) // 2
# 依據(jù)數(shù)組的長(zhǎng)度找到最后一個(gè)父節(jié)點(diǎn): lastParent = len(li) // 2 - 1
3.中序遍歷所有的結(jié)點(diǎn)
def in_order(root):
if not root:
return
print(root.value)
in_order(root.left)
in_order(root.right)
in_order(creatTree(alist))
4.層次遍歷所有的結(jié)點(diǎn)
# 層次遍歷所有的結(jié)點(diǎn)
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)))
希望幫助到有需要的朋友們,方便創(chuàng)建自己的二叉樹-----------------------
同理,
依據(jù)一個(gè)數(shù)組創(chuàng)建一個(gè)鏈表:
# 依據(jù)數(shù)組創(chuàng)建一個(gè)鏈表
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)))
總結(jié)
以上是生活随笔為你收集整理的二叉树层次遍历python_根据二叉树层序遍历顺序(数组),将其转换为二叉树(Python)...的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .sh文件怎么写_typeScript
- 下一篇: python内置方法怎么使用_pytho