二叉搜索树(层序遍历+前\中\后遍历+求最大值)

C++语言实现

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

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

struct Tree {
    Node* root;
};

void Insert(Tree* tree, int value) {
    Node* node = (Node*)malloc(sizeof(Node));
    node->data = value;
    node->left = NULL;
    node->right = NULL;
    
    if(tree->root == NULL)
        tree->root = node;
    else {
        Node* temp = tree->root;
        while(temp != NULL) {
            if(value < temp->data) {
                if(temp->left == NULL) {
                    temp->left = node;
                    return;
                } else {
                    temp = temp->left;
                }
            } else {
                if(temp->right == NULL) {
                    temp->right = node;
                    return;
                } else
                    temp = temp->right;
            }
        }
    }
}

void preorder(Node* node) {
    if(node != NULL) {
        cout << node->data << " ";
        preorder(node->left);
        preorder(node->right);
    }
}

void inorder(Node* node) {
    if(node != NULL) {
        inorder(node->left);
        cout << node->data << " ";
        inorder(node->right);
    }
}

void postorder(Node* node) {
    if(node != NULL) {
        postorder(node->left);
        postorder(node->right);
        cout << node->data << " ";
    }
}

int findMaximum(Node* node) {
    if(node == NULL)
        return -1;
    int value;
    while(node != NULL) {
        value = node->data;
        node = node->right;
    }
    return value;
}

void bfs(Node* node) {
    queue<Node*> q;
    q.push(node);
    while(!q.empty()) {
        Node* temp = q.front();
        cout << temp->data << " ";
        q.pop();
        if(temp->left != NULL)
            q.push(temp->left);
        if(temp->right != NULL)
            q.push(temp->right);
    }
}

int main() {
    Tree tree;
    tree.root = NULL;
    int a[7] = {10, 2, 7, 13, 11, 18, 15};
    for(int i = 0; i < 7; i++) {
        Insert(&tree, a[i]);
    }
    cout << "层序遍历:" << endl;
    bfs(tree.root);
    cout << endl << endl << "先序遍历:" << endl;
    preorder(tree.root);
    cout << endl << endl << "中序遍历:" << endl;
    inorder(tree.root);
    cout << endl << endl << "后序遍历:" << endl;
    postorder(tree.root);
    cout << endl << endl << "二叉搜索树的最大值为:" << endl << findMaximum(tree.root) << endl;
    return 0;
}

实现结果截图

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值