Python TreeNode如何實(shí)現(xiàn)樹的堆排序

小樊
84
2024-08-17 16:25:40
欄目: 編程語言

實(shí)現(xiàn)樹的堆排序可以使用Python中的TreeNode類來表示樹節(jié)點(diǎn),同時(shí)使用堆排序算法來對(duì)樹進(jìn)行排序。以下是一個(gè)示例代碼:

class TreeNode:
    def __init__(self, val=0, left=None, right=None):
        self.val = val
        self.left = left
        self.right = right

def heapify(root, size, i):
    largest = i
    l = 2 * i + 1
    r = 2 * i + 2
    
    if l < size and root[l].val > root[largest].val:
        largest = l
    
    if r < size and root[r].val > root[largest].val:
        largest = r
    
    if largest != i:
        root[i], root[largest] = root[largest], root[i]
        heapify(root, size, largest)

def heap_sort(root):
    size = len(root)
    
    for i in range(size//2 - 1, -1, -1):
        heapify(root, size, i)
    
    for i in range(size-1, 0, -1):
        root[i], root[0] = root[0], root[i]
        heapify(root, i, 0)
    
    return root

# 示例
root = [TreeNode(4), TreeNode(10), TreeNode(7), TreeNode(5), TreeNode(1)]

sorted_root = heap_sort(root)

for node in sorted_root:
    print(node.val)

在上面的代碼中,我們首先定義了TreeNode類來表示樹節(jié)點(diǎn),然后實(shí)現(xiàn)了heapify函數(shù)來維護(hù)堆的性質(zhì),以及heap_sort函數(shù)來對(duì)樹進(jìn)行堆排序。最后我們通過示例代碼對(duì)一個(gè)樹節(jié)點(diǎn)列表進(jìn)行堆排序,并輸出排序后的結(jié)果。

0