เริ่มต้นใช้งานเริ่มต้นใช้งานได้ฟรี

พิมพ์ชื่อหนังสือตามลำดับตัวอักษร

วิดีโอนี้แนะนำวิธีใช้การค้นหาแบบ depth first search ใน binary tree 3 รูปแบบ ได้แก่ in-order, pre-order และ post-order

ใน binary search tree ต่อไปนี้ มีการจัดเก็บชื่อหนังสือหลายเล่มไว้

Graphical representation of a binary search tree.

ต้นไม้ถูกโหลดไว้ล่วงหน้าในตัวแปร bst (บรรทัดที่ 15):

bst = CreateTree()

ลองใช้ in-order traversal เพื่อให้ชื่อหนังสือแสดงผลเรียงตามลำดับตัวอักษร

แบบฝึกหัดนี้เป็นส่วนหนึ่งของหลักสูตร

โครงสร้างข้อมูลและอัลกอริทึมใน Python

ดูคอร์ส

คำแนะนำการฝึกหัด

  • ตรวจสอบว่า current_node มีอยู่หรือไม่
  • เรียกฟังก์ชัน in_order() แบบ recursive บนครึ่งที่เหมาะสมของต้นไม้
  • พิมพ์ค่าของ current_node
  • เรียกฟังก์ชัน in_order() แบบ recursive บนอีกครึ่งหนึ่งของต้นไม้

แบบฝึกหัดเชิงโต้ตอบแบบลงมือทำ

ลองทำแบบฝึกหัดนี้โดยเติมโค้ดตัวอย่างนี้ให้สมบูรณ์

class BinarySearchTree:
  def __init__(self):
    self.root = None

  def in_order(self, current_node):
    # Check if current_node exists
    if ____:
      # Call recursively with the appropriate half of the tree
      self.in_order(current_node.____)
      # Print the value of the current_node
      print(____)
      # Call recursively with the appropriate half of the tree
      self.in_order(current_node.____)
  
bst = CreateTree()
bst.in_order(bst.root)
แก้ไขและรันโค้ด