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

根据二叉树层序遍历顺序(数组),将其转换为二叉树(Python)_第1张图片

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数据结构)