二叉排序树(C++)

问题:

   给定一个结点序列,确定一棵二叉排序树,并给出其前序,中序,后序遍历。

输入:

 5
1 6 5 9 8

思路:

  首先,需要了解二叉排序树的特点。比根节点小的结点在其左子树,比根节点大的结点在其右子树。其中序遍历(左根右)刚好是一个升序序列。

  其次:明白建树过程就是一个插入的过程,有三种情况:1.插入第一个节点,作根节点。2.比根节点的值小,插入其左子树。3.比根节点的值大,插入其右子树。

  最后,遍历。

代码:

#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;
}

结果:

猜你喜欢

转载自blog.csdn.net/Look_star/article/details/99204427