二叉排序樹(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;
}

結果:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章