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

โปรแกรม C++ หาค่าต่ำสุดของ Binary Search Tree

โปรแกรมสำหรับหาค่าต่ำสุดของ Binary Search Tree

อัลกอริทึม

เริ่มต้น
  ประกาศโครงสร้าง nd
  ประกาศ d เป็น integer
  ประกาศ pointer lt ชนิดโครงสร้าง nd
  ประกาศ pointer rt ชนิดโครงสร้าง nd
  ประกาศฟังก์ชัน new_nd() คืนค่าโครงสร้าง nd
  รับพารามิเตอร์ d
  ประกาศ pointer nd ชนิดโครงสร้าง nd
  กำหนด nd = (struct nd*) malloc(sizeof(struct nd))
  nd->d = d
  nd->lt = NULL
  nd->rt = NULL
  คืนค่า nd
สิ้นสุด

เริ่มต้น
  ประกาศฟังก์ชัน add_node() คืนค่าโครงสร้าง nd
  รับพารามิเตอร์ pointer nd และ integer d
  ถ้า nd == NULL คืนค่า new_nd(d)
  มิฉะนั้น ถ้า d <= nd->d แล้ว
    nd->lt = add_node(nd->lt, d)
  มิฉะนั้น
    nd->rt = add_node(nd->rt, d)
  คืนค่า nd
สิ้นสุด

เริ่มต้น
  ประกาศฟังก์ชัน minimum_val() คืนค่า integer
  รับพารามิเตอร์ pointer nd
  ประกาศ pointer cur ชนิดโครงสร้าง nd
  กำหนด cur = nd
  while (cur->lt != NULL) ทำ
    cur = cur->lt
  จบ while
  คืนค่า cur->d
  ประกาศ pointer root ชนิดโครงสร้าง nd
  กำหนด root = NULL
  root = add_node(root, 54)
  add_node(root, 32)
  add_node(root, 25)
  add_node(root, 45)
  add_node(root, 65)
  add_node(root, 75)
  พิมพ์ "The Minimum value of the given binary search tree is: "
  พิมพ์ค่าต่ำสุดของ binary tree
  getchar()
สิ้นสุด

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

#include <bits/stdc++.h>
using namespace std;

struct nd {
    int d;
    struct nd* lt;
    struct nd* rt;
};

struct nd* new_nd(int d) {
    struct nd* nd = (struct nd*) malloc(sizeof(struct nd));
    nd->d = d;
    nd->lt = NULL;
    nd->rt = NULL;
    return nd;
}

struct nd* add_node(struct nd* nd, int d) {
    if (nd == NULL)
        return new_nd(d);
    else {
        if (d <= nd->d)
            nd->lt = add_node(nd->lt, d);
        else
            nd->rt = add_node(nd->rt, d);
        return nd;
    }
}

int minimum_val(struct nd* nd) {
    struct nd* cur = nd;
    while (cur->lt != NULL) {
        cur = cur->lt;
    }
    return cur->d;
}

int main() {
    struct nd* root = NULL;
    root = add_node(root, 54);
    add_node(root, 32);
    add_node(root, 25);
    add_node(root, 45);
    add_node(root, 65);
    add_node(root, 75);
    cout << "The Minimum value of the given binary search tree is: " << minimum_val(root);
    getchar();
    return 0;
}

ผลลัพธ์

The Minimum value of the given binary search tree is: 25