二叉排序树的创建与结点插入(代码实现)

直接看代码,简单易懂不解释:

#include<iostream>
using namespace std;

class Node{
public:
    int value;
    Node* left;
    Node* right;
    Node(){
        left=nullptr;
        right=nullptr;
    }
    Node(int value){
        this->value=value;
        left=nullptr;
        right=nullptr;
    }
    //插入节点
    void add(Node* node){
        if(node==nullptr)
            return;
        if(node->value<this->value){
            //左结点为空就插入左结点,否则往左走
            if(this->left==nullptr){
                this->left=node;
            }else{
                this->left->add(node);
            }
        }else{
            //右节点为空,直接放入插入结点
            if(this->right==nullptr){
                this->right=node;
            }else{
                this->right->add(node);
            }
        }
    }

    void InOrder(Node* root){
        if(root!=nullptr){
            InOrder(root->left);
            cout<<root->value<<" ";
            InOrder(root->right);
        }
    }
};

class Tree{
public:
    Node* root;
    void add(Node* node){
        if(root==nullptr){
            root=node;
        }else
            root->add(node);
    }
    void InOrder(){
        root->InOrder(root);
    }

};

int main(){
    int t;
    cin>>t;
    for(int i=0;i<t;i++){
        Tree* tree=new Tree();
        int n,value;
        cin>>n;
        for(int j=0;j<n;j++){
            cin>>value;
            Node* node=new Node(value);
            tree->add(node);
        }
        tree->InOrder();
    }
    return 0;
}

输入:

1
6
2 3 5 1 8 5

输出:

1 2 3 5 5 8

我是花花,祝自己也祝您变强了~

おすすめ

転載: blog.csdn.net/m0_52711790/article/details/121041466