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

โปรแกรม Python Depth First Search แบบ Post-order Traversal


Post-order Traversal เยี่ยมชม Left → Right → Root ใช้ Recursion สำหรับ General Tree (ไม่ใช่ Binary Tree เท่านั้น)

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

class TreeNode:
    def __init__(self, key):
        self.key = key
        self.children = []
    
    def add_child(self, node):
        self.children.append(node)
    
    def postorder(self):
        for child in self.children:
            child.postorder()
        print(self.key, end=' ')

# Build tree: 5 → (9 → 2)
root = TreeNode(5)
child1 = TreeNode(9)
child1.add_child(TreeNode(2))
root.add_child(child1)

print("Post-order traversal:")
root.postorder()

ผลลัพธ์

Post-order traversal: 2 9 5

คำอธิบาย

  • General Tree: โหนดมีลิสต์ children (ไม่จำกัด 2)

  • Post-order: วนลูป children เรียก postorder() ก่อน แล้วค่อยพิมพ์ตัวเอง

  • ลำดับ: 2 (leaf) → 9 (parent ของ 2) → 5 (root)

  • ใช้ได้กับ Expression Tree, Dependency Resolution, ไฟล์ระบบ