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

โปรแกรม Python หาโหนดที่ N ใน Inorder Traversal ของต้นไม้

เมื่อต้องการหาโหนดที่ N (Nth node) ใน Inorder traversal ของ Binary Tree สามารถทำ traversal แบบ recursive พร้อมนับลำดับ

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

class BinaryTree_struct:
    def __init__(self, key=None):
        self.key = key
        self.left = None
        self.right = None
    
    def set_root(self, key):
        self.key = key
    
    def inorder_nth(self, n):
        return self.inorder_nth_helper_fun(n, [])
    
    def inorder_nth_helper_fun(self, n, in_ord):
        if self.left is not None:
            temp = self.left.inorder_nth_helper_fun(n, in_ord)
            if temp is not None:
                return temp
        in_ord.append(self)
        if n == len(in_ord):
            return self
        if self.right is not None:
            temp = self.right.inorder_nth_helper_fun(n, in_ord)
            if temp is not None:
                return temp
    
    def insert_to_left(self, new_node):
        self.left = new_node
    
    def insert_to_right(self, new_node):
        self.right = new_node
    
    def search_elem(self, key):
        if self.key == key:
            return self
        if self.left is not None:
            temp = self.left.search_elem(key)
            if temp is not None:
                return temp
        if self.right is not None:
            temp = self.right.search_elem(key)
            return temp
        return None

btree_instance = None
print('Menu (this assumes no duplicate keys)')
print('insert  at root')
print('insert  left of ')
print('insert  right of ')
print('inorder ')
print('quit')

while True:
    do = input('What would you like to do? ').split()
    operation = do[0].strip().lower()
    if operation == 'insert':
        data = int(do[1])
        new_node = BinaryTree_struct(data)
        suboperation = do[2].strip().lower()
        if suboperation == 'at':
            btree_instance = new_node
        else:
            position = do[4].strip().lower()
            key = int(position)
            ref_node = None
            if btree_instance is not None:
                ref_node = btree_instance.search_elem(key)
            if ref_node is None:
                print('No such key.')
                continue
            if suboperation == 'left':
                ref_node.insert_to_left(new_node)
            elif suboperation == 'right':
                ref_node.insert_to_right(new_node)
    elif operation == 'inorder':
        if btree_instance is not None:
            index = int(do[1].strip().lower())
            node = btree_instance.inorder_nth(index)
            if node is not None:
                print('nth term of inorder traversal: {}'.format(node.key))
            else:
                print('The index exceeds maximum possible index.')
        else:
            print('The tree is empty...')
    elif operation == 'quit':
        break

ผลลัพธ์ตัวอย่าง

Menu (this assumes no duplicate keys)
insert  at root
insert  left of 
insert  right of 
inorder
quit
What would you like to do? insert 5 at root
What would you like to do? insert 6 left of 5
What would you like to do? insert 8 right of 5
What would you like to do? inorder 5
The index exceeds maximum possible index.
What would you like to do? 6 6

คำอธิบาย

  • คลาส BinaryTree_struct: โหนด binary tree พื้นฐาน

  • เมธอด inorder_nth: เรียก helper function พร้อม list ว่างสำหรับเก็บลำดับ

  • เมธอด inorder_nth_helper_fun: ทำ inorder traversal แบบ recursive พร้อมตรวจสอบลำดับ

  • เมธอด insert_to_left/right: เพิ่มลูกซ้าย/ขวา

  • เมธอด search_elem: ค้นหาโหนดด้วย key

  • โปรแกรมหลักรับคำสั่ง interactive สร้างต้นไม้และ query Nth node

ข้อสังเกต: ผลลัพธ์ตัวอย่างบรรทัดสุดท้าย What would you like to do? 6 6 ดูเหมือนจะเป็นข้อผิดพลาดในการบันทึก (ควรเป็นคำสั่ง inorder 2 หรือคล้ายๆ) และ output แสดงแค่ 6 ซึ่งคือคำตอบสำหรับ inorder 2 (ลำดับที่ 2 คือ 6)