华科机考:二叉排序树

时间限制:1秒    空间限制:32768K

题目描述

输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。

输入描述: 输入第一行包括一个整数n(1<=n<=100)。 接下来的一行包括n个整数。

输出描述: 可能有多组测试数据,对于每组数据,将题目所给数据建立一个二叉排序树,并对二叉排序树进行前序、中序和后序遍历。 每种遍历结果输出一行。每行最后一个数据之后有一个空格。

输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。

输入例子: 5

             1 6 5 9 8

输出例子: 1 6 5 9 8

              1 5 6 8 9

              5 8 9 6 1

思路:1.建立一颗二叉排序树需要首先查找,没有才能插入该元素,二叉排序树的查找效率很高(每次递归只有一个分支),具体实现的时候需要4个参数来实现查找过程,当前节点,要查找的键值,当前节点的父亲节点,还有一个为了返回出查找到的节点的相关信息(引用)(当前节点或者是当前节点的父亲节点)。

        2.插入时要注意一下,如果返回的父亲节点为空(此时一个节点都没有)需要单独判断一下

代码:

      

#include <iostream>
#include <stdio.h>
using namespace std;

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

int SearchBSF(node *current,int key,node *f,node *&p){
    if(current==NULL){
     p=f;
     return 0;
    }
    else{
    if(current->data==key){
     p=current;
     return 1;
    }
    else if(current->data>key)
    return SearchBSF(current->left,key,current,p);
    else
    return SearchBSF(current->right,key,current,p);
    }
}

void InsertBSF(node *&root,int key){
    node *p;
    if(SearchBSF(root,key,NULL,p)==0){
    node *tmp=new node;
    tmp->data=key;
    tmp->left=NULL;
    tmp->right=NULL;
    if(p==NULL)
    root=tmp;
    else{
    if(key>p->data)
      p->right=tmp;
    else
      p->left=tmp;
    }
}
}

void pre_order(node *root){
    if(root!=NULL){
    cout<<root->data<<" ";
    pre_order(root->left);
    pre_order(root->right);
    }
    else
    return;
}

void in_order(node *root){
    if(root!=NULL){
    in_order(root->left);
    cout<<root->data<<" ";
    in_order(root->right);
    }
    else
    return;
}

void post_order(node *root){
    if(root!=NULL){
    post_order(root->left);
    post_order(root->right);
    cout<<root->data<<" ";
    }
    else
    return;
}

int main(){
    int n,data;
    node *root;
    while(cin>>n){
    root=NULL;
    while(n--){
    cin>>data;
    InsertBSF(root,data);
    }
    pre_order(root);
    cout<<endl;
    in_order(root);
    cout<<endl;
    post_order(root);
    cout<<endl;
    }
}
原文地址:https://www.cnblogs.com/mlgjb/p/6718493.html