Binary Sort Tree (C++)

problem:

   Given a node sequence, determine a binary sort tree, and give its preorder, middle order, and postorder traversal.

enter:

 5
1 6 5 9 8

Ideas:

  First of all, you need to understand the characteristics of a binary sort tree. Nodes smaller than the root node are in its left subtree, and nodes larger than the root node are in its right subtree. The order traversal (left root right) is just an ascending sequence.

  Second: understand that the process of building a tree is an insertion process, there are three situations: 1. Insert the first node as the root node. 2. If the value is smaller than the root node, insert its left subtree. 3. If the value is greater than the root node, insert its right subtree.

  Finally, traverse.

Code:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>

using namespace std;

int n,x;


struct Node{
    int value;
    Node* lchild;
    Node* rchild;
};


Node* insertNode(Node* root,int x)
{
    if(root==NULL)//为空建树
    {
        root=new Node({x,NULL,NULL});
        return root;
    }
    if(x<root->value)//小于插左子树
        root->lchild=insertNode(root->lchild,x);
    else if(x>root->value)//大于插右子树
        root->rchild=insertNode(root->rchild,x);
    return root;

}

void preTraverse(Node* root)
{
    if(root==NULL)
        return;
    cout<<root->value<<" ";
    if(root->lchild!=NULL)
        preTraverse(root->lchild);
    if(root->rchild!=NULL)
        preTraverse(root->rchild);
}

void inTraverse(Node* root)
{
    if(root==NULL)
        return;
    if(root->lchild!=NULL)
        inTraverse(root->lchild);
    cout<<root->value<<" ";
    if(root->rchild!=NULL)
        inTraverse(root->rchild);
}
void postTraverse(Node* root)
{
    if(root==NULL)
        return;
    if(root->lchild!=NULL)
        postTraverse(root->lchild);
    if(root->rchild!=NULL)
        postTraverse(root->rchild);
    cout<<root->value<<" ";
}




int main()
{
    cin>>n;
    Node* root=NULL;
    while(n--)
    {
        cin>>x;
        root=insertNode(root,x);
    }
    cout<<"Pre: ";
    preTraverse(root);
    cout<<endl;
    cout<<"In: ";
    inTraverse(root);
    cout<<endl;
    cout<<"Post: ";
    postTraverse(root);
    cout<<endl;

    return 0;
}

result:

 

Guess you like

Origin blog.csdn.net/Look_star/article/details/99204427