数据结构与算法经典题型总结

约瑟夫环问题

数组(顺序存储)

用顺序存储表示(数组)实现约瑟夫环问题。

约瑟夫问题的一种描述:编号为1,2,…,n的n个人按顺时针方向围坐一圈,每人持有一个密码(正整数)。一开始任选一个正整数作为报数的上限值m,从第一个人开始按顺时针方向自1开始顺序报数。

方法1,报数为m的人出列(将其删除),从他在顺时针方向上的下一个人开始重新从1报数……如此下去,直到所有人全部出列为止。试设计一个程序求出出列顺序。要求利用单向循环链表存储结构模拟此过程,按照出列的顺序打印出各人的编号和此人密码。

方法2,报m的人出列(将其删除),将他的密码作为新的m值,从他在顺时针方向上的下一个人开始重新从1报数……如此下去,直到所有人全部出列为止。试设计一个程序求出出列顺序。要求利用单向循环链表存储结构模拟此过程,按照出列的顺序打印出各人的编号。

#include <iostream>
#include <vector>

using namespace std;

// 定义一个结构体来表示每个人
struct Person {
    int id;
    int password;
};

// 方法1:报数为m的人出列,从下一个人开始重新从1报数
void josephusMethod1(int n, int m) {
    vector<Person> people(n);

    // 初始化人员信息
    for (int i = 0; i < n; ++i) {
        people[i].id = i + 1;
        people[i].password = rand() % 1000; // 假设密码是一个随机整数
    }

    int current = 0; // 当前报数的人的索引
    while (n > 0) {
        // 报数m-1次
        for (int i = 1; i < m; ++i) {
            current = (current + 1) % n;
        }

        // 输出出列的人的编号和密码
        cout << "出列:" << people[current].id << ",密码:" << people[current].password << endl;

        // 将出列的人从数组中移除
        people.erase(people.begin() + current);

        // 更新人数
        n--;
    }
}

// 方法2:报m的人出列,将他的密码作为新的m值
void josephusMethod2(int n, int m) {
    vector<Person> people(n);

    // 初始化人员信息
    for (int i = 0; i < n; ++i) {
        people[i].id = i + 1;
        people[i].password = rand() % 1000; // 假设密码是一个随机整数
    }

    int current = 0; // 当前报数的人的索引
    while (n > 0) {
        // 报数m-1次
        for (int i = 1; i < m; ++i) {
            current = (current + 1) % n;
        }

        // 输出出列的人的编号和密码
        cout << "出列:" << people[current].id << ",密码:" << people[current].password << endl;

        // 更新m值为出列的人的密码
        m = people[current].password;

        // 将出列的人从数组中移除
        people.erase(people.begin() + current);

        // 更新人数
        n--;
    }
}

int main() {
    int n, m;
    cout << "请输入总人数n和初始报数值m:" << endl;
    cin >> n >> m;

    cout << "方法1的出列顺序:" << endl;
    josephusMethod1(n, m);

    cout << "方法2的出列顺序:" << endl;
    josephusMethod2(n, m);

    return 0;
}

在这里插入图片描述

链表

typedef struct node             /*  结点的结构定义  */ 
   {  int  num;              /*  编号子域        */
      struct node *next;        /*  指针域          */ 
   }JOS;

void outs(JOS  *h, int m)
{  int i;   JOS *q=h,  *p; 
  printf(“\n “); 
  while (q->next!=q)
   { for(i=1;i<m;i++){ p=q; q=q->next;}       /*  报数到第m个人 */
     printf(%6d”,q->num);        /*  输出第m个人的编号  */
     p->next=q->next;  free(q);             /*  第m个人出列  */
     q=p->next;
    }
  printf(%6d  \n”,q->num);           /*  输出最后一个结点的编号值  */
  free(q);
} /* outs  */

通讯录

链表

用链表建立通讯录。通讯录内容有姓名、通讯地址、电话号码。要求:
(1) 通讯录是按姓名项的字母顺序排列的; (2) 能查找通讯录中某人的信息。
[提示]
可用链表来存放这个通讯录,一个人的信息作为一个结点。成链的过程可以这样考虑:先把头结点后面的第一个数据元素结点作为链中的首结点,也是末结点。从第二个数据开始逐一作为“工作结点”,需从链表的首结点开始比较,如果“工作结点”的数据元素的姓名字符串比链中的“当前结点”的数据元素的姓名字符串小,就插在其前面。否则,再看后面是否还有结点,若没有结点了就插在其后面成为末结点;若后面还有结点,再与后面的结点逐一比较处理。

#include <iostream>
#include <string>

using namespace std;

// 定义通讯录节点
struct ContactNode {
    string name;
    string address;
    string phoneNumber;
    ContactNode* next;

    // 构造函数
    ContactNode(const string& n, const string& addr, const string& phone)
        : name(n), address(addr), phoneNumber(phone), next(nullptr) {}
};

// 插入通讯录节点,按姓名字母顺序排列
void insertContact(ContactNode*& head, const string& name, const string& address, const string& phoneNumber) {
    ContactNode* newNode = new ContactNode(name, address, phoneNumber);

    // 如果头结点为空或新节点的姓名比头结点小,则将新节点作为头结点
    if (head == nullptr || name < head->name) {
        newNode->next = head;
        head = newNode;
        return;
    }

    // 否则,遍历链表找到正确的插入位置
    ContactNode* current = head;
    while (current->next != nullptr && name > current->next->name) {
        current = current->next;
    }

    // 插入新节点
    newNode->next = current->next;
    current->next = newNode;
}

// 查找通讯录中的联系人信息
void findContact(const ContactNode* head, const string& name) {
    const ContactNode* current = head;
    bool found = false;

    while (current != nullptr) {
        if (current->name == name) {
            cout << "姓名: " << current->name << endl;
            cout << "地址: " << current->address << endl;
            cout << "电话号码: " << current->phoneNumber << endl;
            found = true;
            break;
        }
        current = current->next;
    }

    if (!found) {
        cout << "未找到名为 " << name << " 的联系人。" << endl;
    }
}

// 打印整个通讯录
void printContactList(const ContactNode* head) {
    const ContactNode* current = head;

    cout << "通讯录内容:" << endl;
    while (current != nullptr) {
        cout << "姓名: " << current->name << endl;
        cout << "地址: " << current->address << endl;
        cout << "电话号码: " << current->phoneNumber << endl;
        cout << "-----------------------" << endl;
        current = current->next;
    }
}

int main() {
    ContactNode* contactList = nullptr;

    // 添加联系人
    insertContact(contactList, "John Smith", "123 Main St", "555-1234");
    insertContact(contactList, "Alice Johnson", "456 Elm St", "555-5678");
    insertContact(contactList, "Bob Brown", "789 Oak St", "555-9876");

    // 打印通讯录
    printContactList(contactList);

    // 查找联系人
    string searchName = "Alice Johnson";
    findContact(contactList, searchName);

    // 清理内存
    while (contactList != nullptr) {
        ContactNode* temp = contactList;
        contactList = contactList->next;
        delete temp;
    }

    return 0;
}

在这里插入图片描述

代码逆置

链表头插法

typedef struct node             /*  结点的结构定义  */ 
   {  int  num;              /*  编号子域        */
      struct node *next;        /*  指针域          */ 
   }Linknode;
void Reverse(LinkNode*& L)
{
    LinkNode* p = L->next, * q;
    L->next = NULL;
	while (p != NULL) //扫描所有的结点 

    {
        q = p->next; //q 临时保存 p 结点的后继结点
		p->next = L->next; //总是将 p 结点作为首结点插入​ 
		L->next = p;
		p = q; //让 p 指向下一个结点
    }
}

顺序表

typedef struct
{
int *elem;
int length;
} SqList;
//核心代码
void Inverse(SqList &L) {
	int i, temp;
	for (i = 0; i < L.length / 2; i++) {
		temp = L.elem[i];
		L.element[i] = L.elem[L.length - 1 - i];
		L.element[L.length - 1 - i] = temp;
	}
}

递归算法& 栈替代递归结构

请添加图片描述
请添加图片描述
请添加图片描述

请添加图片描述
请添加图片描述
请添加图片描述

阿克曼函数

阿克曼函数(Ackermann’s function)定义如下:

在这里插入图片描述

人们之所以研究该函数,是因为m和n值的较小增长都会引起函数值的极快增长。

(1) 设计运用递归算法的源程序,上机运行。

(2) 写一个非递归算法的源程序,上机运行,并进行比较。
递归

#include <iostream>

int ackermann_recursive(int m, int n) {
    if (m == 0) {
        return n + 1;
    } else if (m > 0 && n == 0) {
        return ackermann_recursive(m - 1, 1);
    } else if (m > 0 && n > 0) {
        return ackermann_recursive(m - 1, ackermann_recursive(m, n - 1));
    }
}

int main() {
    int m = 3;
    int n = 3;
    int result = ackermann_recursive(m, n);
    std::cout << "A(" << m << ", " << n << ") = " << result << std::endl;
    return 0;
}

非递归

#include <iostream>
#include <stack>

int ackermann_non_recursive(int m, int n) {
    std::stack<std::pair<int, int>> stack;
    while (m > 0) {
        if (n == 0) {
            m -= 1;
            n = 1;
        } else {
            stack.push(std::make_pair(m - 1, n));
            n = ackermann_non_recursive(m, n - 1);
        }
    }
    while (!stack.empty()) {
        std::pair<int, int> p = stack.top();
        stack.pop();
        m = p.first;
        n = p.second;
        n = ackermann_non_recursive(m, n);
    }
    return n + 1;
}

int main() {
    int m = 3;
    int n = 3;
    int result = ackermann_non_recursive(m, n);
    std::cout << "A(" << m << ", " << n << ") = " << result << std::endl;
    return 0;
}

字符串逆序存储

#define MAXLEN 255 //预定义最大串长

typedef struct{ 
char ch[MAXLEN];//每个分量存储一个字符
int length;//串的实际长度

}str;

void Reversstr(std::string:&str,int start,int end)

{
/* 初始 start=0;
end=length-1;*/
std::swap(str[start],str[end]);
Reversstr(str,start+1,end-1)

}


KMP算法

编写算法,从串s中删除所有和串t相同的子串。

void KMPStrAlt(string S,  string T)
{
    
    int next[20], i, j, k;
   
    Getnext(T, next);
    j = 0;
    while (i < unsigned(S.length()) && j <unsigned( T.length()))
    {
        if (j == -1 || S[i] == T[j])
        {
            i++, j++;
        }
        else
            j = next[j];
        if (j == T.length())
        {
            k = i - T.length() + 1;
            S.erase(i - T.length() + 1, T.length());
            int n = S.length(); // Update the length of the string
        }
    }

}
void Getnext(string t, int next[])
{
    int j = 0, k = -1;
    next[0] = -1;
    while (j < t.length())
        if (k == -1 || t[j] == t[k])
        {
            next[++j] = ++k;
        }
        else
        {
            k = next[k];
        }


设计可以在主串 s 中第 i 个位置插入一个子串 t 的程序。

#include <iostream>
#include <string>

std::string insertSubstring(const std::string &s, const std::string &t, int i) {
    if (i < 0 || i > s.length()) {
        std::cerr << "Invalid position for insertion." << std::endl;
        return s; // Return the original string if the position is invalid
    }

    std::string result;
    result.reserve(s.length() + t.length()); // Reserve memory for the result string

    // Copy characters from the beginning of s to the insertion point
    result.append(s, 0, i);

    // Append the substring t to the result
    result += t;

    // Copy the remaining characters from s to the result
    result.append(s, i, s.length() - i);

    return result;
}

int main() {
    std::string s = "Hello, World!";
    std::string t = "Beautiful ";
    int i = 7;

    std::string result = insertSubstring(s, t, i);

    std::cout << "Original String: " << s << std::endl;
    std::cout << "Substring to Insert: " << t << std::endl;
    std::cout << "Position for Insertion: " << i << std::endl;
    std::cout << "Resulting String: " << result << std::endl;

    return 0;
}

数组和广义表

稀疏矩阵和三元组顺序表

假设稀疏矩阵A和B均以三元组顺序表作为存储结构。试写出矩阵相加的算法,另设三元组表C存放结果矩阵。

#include <iostream>
using namespace std;

#define MAXSIZE 999
#define MAXRC 10

// 三元组结构体
typedef struct {
    int i, j;  // 所在行数,列数
    int v;     // 值
} triple;

// 存储矩阵的三元组顺序表
typedef struct {
    triple data[MAXSIZE + 1];  // 存储数据
    int mu, nu, tu;            // 存储矩阵的行数,列数和非 0 元的个数
} TSMatrix;

// 矩阵相加算法
void MatrixAddition(const TSMatrix &A, const TSMatrix &B, TSMatrix &C) {
    // 判断两个矩阵是否可以相加
    if (A.mu != B.mu || A.nu != B.nu) {
        cout << "Error: Matrix dimensions do not match." << endl;
        return;
    }

    // 初始化结果矩阵C
    C.mu = A.mu;
    C.nu = A.nu;
    C.tu = 0;

    // 遍历A和B的三元组表,逐元素相加
    int pA = 1, pB = 1;
    while (pA <= A.tu && pB <= B.tu) {
        if (A.data[pA].i < B.data[pB].i || (A.data[pA].i == B.data[pB].i && A.data[pA].j < B.data[pB].j)) {
            // A中的元素较小,将其加入C
            C.data[++C.tu] = A.data[pA++];
        } else if (A.data[pA].i > B.data[pB].i || (A.data[pA].i == B.data[pB].i && A.data[pA].j > B.data[pB].j)) {
            // B中的元素较小,将其加入C
            C.data[++C.tu] = B.data[pB++];
        } else {
            // A和B中的元素坐标相同,进行相加
            int sum = A.data[pA].v + B.data[pB].v;
            if (sum != 0) {
                // 非零元素才加入C
                C.data[++C.tu].i = A.data[pA].i;
                C.data[C.tu].j = A.data[pA].j;
                C.data[C.tu].v = sum;
            }
            pA++;
            pB++;
        }
    }

    // 将A或B中剩余的元素加入C
    while (pA <= A.tu) {
        C.data[++C.tu] = A.data[pA++];
    }

    while (pB <= B.tu) {
        C.data[++C.tu] = B.data[pB++];
    }
}

// 打印稀疏矩阵
void PrintMatrix(const TSMatrix &matrix) {
    for (int i = 1; i <= matrix.tu; i++) {
        cout << matrix.data[i].i << " " << matrix.data[i].j << " " << matrix.data[i].v << endl;
    }
}

int main() {
    // 初始化矩阵A
    TSMatrix A;
    A.mu = 3;
    A.nu = 3;
    A.tu = 3;
    A.data[1] = {1, 1, 2};
    A.data[2] = {2, 2, 3};
    A.data[3] = {3, 3, 4};

    // 初始化矩阵B
    TSMatrix B;
    B.mu = 3;
    B.nu = 3;
    B.tu = 3;
    B.data[1] = {1, 1, 1};
    B.data[2] = {2, 2, 2};
    B.data[3] = {3, 3, 3};

    // 初始化结果矩阵C
    TSMatrix C;

    // 执行矩阵相加算法
    MatrixAddition(A, B, C);

    // 打印结果矩阵C
    cout << "Matrix C:" << endl;
    PrintMatrix(C);

    return 0;
}

三元组顺序表的插入

假设系数矩阵 A 和 B 均以三元组顺序表作为存储结构。试写出满足以下条件的矩阵相加的算法:假设三元组顺序表 A 的空间足够大,将矩阵 B 加到矩阵 A 上,不增加 A、B 之外的附加空间,你的算法能否达到 O(m+n) 的时间复杂度? 其中 m 和 n 分别为 A 、B 矩阵中非零元的数目。

#include <iostream>
using namespace std;

#define MAXSIZE 999
#define MAXRC 10

// 三元组结构体
typedef struct {
    int i, j;  // 所在行数,列数
    int v;     // 值
} triple;

// 存储矩阵的三元组顺序表
typedef struct {
    triple data[MAXSIZE + 1];  // 存储数据
    int mu, nu, tu;            // 存储矩阵的行数,列数和非 0 元的个数
} TSMatrix;

// 将矩阵B加到矩阵A上的算法
void AddMatrix(TSMatrix &A, const TSMatrix &B) {
    // 判断两个矩阵是否可以相加
    if (A.mu != B.mu || A.nu != B.nu) {
        cout << "Error: Matrix dimensions do not match." << endl;
        return;
    }

    // 初始化结果矩阵C
    A.tu = 0;

    // 遍历B的三元组表,逐元素相加
    int pB = 1;
    while (pB <= B.tu) {
        int i = B.data[pB].i;
        int j = B.data[pB].j;
        int value = B.data[pB].v;

        // 在A中查找相同位置的元素
        int pA = 1;
        while (pA <= A.tu && (A.data[pA].i < i || (A.data[pA].i == i && A.data[pA].j < j))) {
            pA++;
        }

        // 判断A中是否有相同位置的元素
        if (pA <= A.tu && A.data[pA].i == i && A.data[pA].j == j) {
            // 相同位置的元素存在,进行相加
            A.data[pA].v += value;
            if (A.data[pA].v == 0) {
                // 如果相加后为零,删除该元素
                for (int k = pA; k < A.tu; k++) {
                    A.data[k] = A.data[k + 1];
                }
                A.tu--;//三元组元素集体向前挪。
            }
        } else {
            // 相同位置的元素不存在,插入新元素
            if (A.tu < MAXSIZE) {
                int k = A.tu;
                while (k >= pA) {
                    A.data[k + 1] = A.data[k];
                    k--;//三原子元素集体向后挪移位。
                }
                A.data[pA].i = i;
                A.data[pA].j = j;
                A.data[pA].v = value;
                A.tu++;
            } else {
                cout << "Error: Result matrix exceeds maximum size." << endl;
                return;
            }
        }

        pB++;
    }
}

// 打印稀疏矩阵
void PrintMatrix(const TSMatrix &matrix) {
    for (int i = 1; i <= matrix.tu; i++) {
        cout << matrix.data[i].i << " " << matrix.data[i].j << " " << matrix.data[i].v << endl;
    }
}

int main() {
    // 初始化矩阵A
    TSMatrix A;
    A.mu = 3;
    A.nu = 3;
    A.tu = 3;
    A.data[1] = {1, 1, 2};
    A.data[2] = {2, 2, 3};
    A.data[3] = {3, 3, 4};

    // 初始化矩阵B
    TSMatrix B;
    B.mu = 3;
    B.nu = 3;
    B.tu = 3;
    B.data[1] = {1, 1, 1};
    B.data[2] = {2, 2, 2};
    B.data[3] = {3, 3, 3};

    // 执行将矩阵B加到矩阵A上的算法
    AddMatrix(A, B);

    // 打印结果矩阵A
    cout << "Matrix A after addition:" << endl;
    PrintMatrix(A);

    return 0;
}

稀疏矩阵和十字链表

试编写一个以三元组形式输出用十字链表表示的稀疏矩阵中非零元素及其下标的算法。

#include <iostream>
using namespace std;

#define MAXRC 10

// 十字链表结点结构体
typedef struct OLNode {
    int i, j;           // 行号和列号
    int e;              // 元素值
    struct OLNode *right, *down;  // 向右和向下指针
} OLNode;

// 十字链表表示的稀疏矩阵
typedef struct {
    OLNode *rhead[MAXRC];  // 行表头指针数组
    OLNode *chead[MAXRC];  // 列表头指针数组
    int mu, nu, tu;        // 行数,列数,非零元个数
} CrossList;

// 创建稀疏矩阵的十字链表
void CreateCrossList(CrossList &M, int A[MAXRC][MAXRC], int mu, int nu) {
    M.mu = mu;
    M.nu = nu;
    M.tu = 0;

    // 初始化行、列头指针数组
    for (int i = 0; i < MAXRC; i++) {
        M.rhead[i] = nullptr;
        M.chead[i] = nullptr;
    }

    // 构建十字链表
    for (int i = 0; i < mu; i++) {
        for (int j = 0; j < nu; j++) {
            if (A[i][j] != 0) {
                // 创建结点
                OLNode *node = new OLNode;
                node->i = i;
                node->j = j;
                node->e = A[i][j];
                node->right = nullptr;
                node->down = nullptr;

                // 插入到行链表
                if (M.rhead[i] == nullptr || M.rhead[i]->j > j) {
                    node->right = M.rhead[i];
                    M.rhead[i] = node;
                } else {
                    OLNode *pre = M.rhead[i];
                    while (pre->right != nullptr && pre->right->j < j) {
                        pre = pre->right;//该指针从hang头节点一直移动到离新节点最近的位置,且在新节点的左边。
                    }
                    node->right = pre->right;
                    pre->right = node;
                }

                // 插入到列链表
                if (M.chead[j] == nullptr || M.chead[j]->i > i) {
                    node->down = M.chead[j];
                    M.chead[j] = node;
                } else {
                    OLNode *pre = M.chead[j];
                    while (pre->down != nullptr && pre->down->i < i) {
                        pre = pre->down;//该指针从lie头节点一直移动到离心结点最近的位置,且在新节点的上边。
                    }
                    node->down = pre->down;
                    pre->down = node;
                }

                M.tu++;
            }
        }
    }
}

// 输出稀疏矩阵的三元组形式
void PrintCrossList(const CrossList &M) {
    cout << "Non-zero elements in sparse matrix:" << endl;
    for (int i = 0; i < M.mu; i++) {
        OLNode *node = M.rhead[i];
        while (node != nullptr) {
            cout << "(" << node->i << ", " << node->j << ", " << node->e << ")" << endl;
            node = node->right;
        }
    }
}

int main() {
    int A[MAXRC][MAXRC] = {
        {0, 0, 3, 0, 0},
        {0, 0, 0, 4, 0},
        {0, 0, 0, 0, 5},
        {0, 0, 0, 0, 0},
        {0, 2, 0, 0, 0}
    };

    CrossList M;
    CreateCrossList(M, A, 5, 5);

    PrintCrossList(M);

    return 0;
}

创建节点:为矩阵中的每个非零元素创建一个新的OLNode。节点存储行(i)、列(j)和元素值(e)。

插入行列表(rhead[i]):对于第i行,程序将节点插入到行列表中。如果行列表为空(M.rhead[i] == nullptr)或第一个节点的列大于当前列(M.rhead[i]->j >j),则新节点成为行列表的新表头。否则,程序会在行列表中找到适当的位置来插入节点,并保持列索引的升序。

插入列表(head[j]):对于每一列j,程序将节点插入列表。与行插入逻辑类似,如果列列表为空,或者第一个节点的行大于当前行,则新节点成为列列表的新表头。否则,程序会在列列表中找到适当的位置来插入节点,并保持行索引的升序。

递增非零元素数量(M.tu++):在矩阵中成功插入一个非零元素后,递增矩阵的非零元素数量tu。

这个过程确保元素正确地插入到行和列列表中,并按行和列索引保持顺序。

数和二叉树

二叉搜索树

深度

#include <iostream>
#include <queue>
using namespace std;

struct BstNode* GetNewNode(int data);//创建新节点
struct BstNode* Insert(BstNode* root, int data);//插入搜索树节点
bool Search(BstNode* root, int data);//查找结点
int GetMin(BstNode* root);//二叉搜索树找最小值
int FindHeight(struct BstNode* root);//求树的深度
void LeverOrder(BstNode* root);//层序遍历
void InOrder(BstNode* root);//中序遍历
bool IsBst(BstNode* root, int min_value, int max_value);//判断一个二叉树是否为bst

struct BstNode
{
	int data;
	BstNode* left;
	BstNode* right;
};

struct BstNode* GetNewNode(int data)
{
	BstNode* newNode = new BstNode();
	newNode->data = data;
	newNode->left = newNode->right = NULL;
	return newNode;
}


struct BstNode* Insert(BstNode *root,int data)
{
	if (root == NULL)
	{
		root = GetNewNode(data);
		
    }
	else if ( data<=root->data)
	{
		root->left = Insert(root->left, data);
	}
	else 
	{
		root->right = Insert(root->right,data);
	}
	return root;
}


bool Search(BstNode* root, int data)
{
	if (root == NULL)
	{
		return false;
	}
	else if (root->data == data)
	{
		return true;
	}
	else if (data <= root->data)
	{
		return Search(root->left, data);
	}
	else
	{
		return Search(root->right, data);
	}
}

int GetMin(BstNode *root)
{
	if (root->left == NULL)
	{
		return root->data;
	}
	else
	{
		root = root->left;
		GetMin(root);
		
	}

}
int GetMax(BstNode* root)
{
	if (root->right == NULL)
	{
		return root->data;
	}
	else
	{
		root = root->right;
		GetMin(root);

	}

}



int i, j = 1;

int FindHeight(struct BstNode* root)
{
	
	if (root == NULL)
	{		return 0;
	}
	else
	{
		/*while (root->left != NULL)
		{
			root = root->left;
			FindHeight(root);
			++i;
		}
		while (root->right != NULL)
		{
			root = root->right;
			FindHeight(root);
			++j;
		}
		int height = (i >= j ? i : j);*/

		return max(   FindHeight(root->left),FindHeight(root->right)  )+1;
	}
}

void LeverOrder(BstNode* root)
{
	if (root == NULL)
	{
		return;
    }
	queue<BstNode*> Q;
	Q.push(root);
	while (!Q.empty())
	{
		BstNode* current = Q.front();
		cout << current->data << endl;
		if (current->left != NULL) { Q.push(current->left); }
		if (current->right != NULL) { Q.push(current->right); }
		Q.pop();

	}
}

void InOrder(BstNode* root)//中序遍历
{
	if (root == NULL)
	{
		return ;
	}
	InOrder(root->left);
	cout << root->data<<" ";
	InOrder(root->right);
}

bool IsBst(BstNode* root, int min_value, int max_value)
{
	if (root == NULL)
	{
		return 1;
	}
	if (root->data > min_value && root->data < max_value && IsBst(root->left, min_value,root->data) && IsBst(root->right, root->data,max_value))
	{
		return 1;
	}
	else 
		return 0;
}


int main()
{
 int max_value=100;
 int min_value=-100;

	BstNode* root = NULL;
	root = Insert(root, 15);
	root = Insert(root, 10);
	root = Insert(root, 20);
	root = Insert(root, 25);
	root = Insert(root, 8);
	root = Insert(root, 12);
	/*int number;
	cout << "Enter the number u wanna search:" << endl;
	cin >> number;
	if (Search(root, number) == true)
		cout << "Found\n";
	else
		cout << "NOt Founs\n";*/
	cout << "Find the minNumber:\n"<<GetMin(root)<<endl;
	cout << "Find the maxNumber:\n" << GetMax(root)<<endl;

	int height=FindHeight(root);
	cout << "The height of the tree is:" << height << endl;
	cout << "按层遍历:" << endl;

	LeverOrder(root);
	cout << "中序遍历\n";
	InOrder(root);
	
	if (IsBst(root, min_value, max_value) == 1)
	{
		cout << "this is bst" << endl;
	}
	else
		cout << "this in not bst" << endl;

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值