二叉树层次遍历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)...的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: .sh文件怎么写_typeScript
- 下一篇: python内置方法怎么使用_pytho