Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

สร้าง Mirror Copy ของ Binary Tree และแสดงด้วย BFS ใน Python


Mirror Tree คือต้นไม้ที่ลูกซ้ายและลูกขวาของทุกโหนดถูกสลับกัน สร้างโดย Recursion แล้วแสดงด้วย BFS

ตัวอย่างโค้ด

from collections import deque

class Node:
    def __init__(self, key):
        self.key = key
        self.left = None
        self.right = None
    
    def mirror_copy(self):
        new_node = Node(self.key)
        if self.right:
            new_node.left = self.right.mirror_copy()
        if self.left:
            new_node.right = self.left.mirror_copy()
        return new_node
    
    def bfs(self):
        q = deque([self])
        while q:
            n = q.popleft()
            print(n.key, end=' ')
            if n.left: q.append(n.left)
            if n.right: q.append(n.right)

# Original tree
root = Node(6)
root.left = Node(9)
root.right = Node(4)

print("Original BFS:")
root.bfs()
print()

mirror = root.mirror_copy()
print("Mirror BFS:")
mirror.bfs()

ผลลัพธ์

Original BFS: 6 9 4
Mirror BFS: 6 4 9

คำอธิบาย

  • mirror_copy() สร้างโหนดใหม่คีย์เดียวกัน

  • ลูกซ้ายของ mirror = mirror_copy ของลูกขวาเดิม

  • ลูกขวาของ mirror = mirror_copy ของลูกซ้ายเดิม

  • BFS แสดงระดับ: Original (6,9,4) → Mirror (6,4,9)

  • ต้นไม้เดิมไม่ถูกแก้ไข (สร้าง copy ใหม่)