zoukankan      html  css  js  c++  java
  • 二叉排序树

    题目描述:
        输入一系列整数,建立二叉排序数,并进行前序,中序,后序遍历。
    输入:
        输入第一行包括一个整数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
    提示:
    输入中可能有重复元素,但是输出的二叉树遍历序列中重复元素不用输出。
     
    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
     
    struct node {
    node *lchild;
    node *rchild;
    int c;
    }tree[110];
     
    int loc;
     
    node* creat(){
    tree[loc].lchild = tree[loc].rchild = NULL;
    loc++;
    return &tree[loc-1];
    }
     
    void post(node *t){
    if (t->lchild){
    post(t->lchild);
    }
    if (t->rchild){
    post(t->rchild);
    }
    printf ("%d ",t->c);
    }
     
    void mid(node *t){
    if (t->lchild){
    mid(t->lchild);
    }
    printf ("%d ",t->c);
    if (t->rchild){
    mid(t->rchild);
    }
    }
     
    void pre(node *t){
    printf ("%d ",t->c);
    if (t->lchild){
    pre(t->lchild);
    }
    if (t->rchild){
    pre(t->rchild);
    }
    }
    node * insert (node *t, int x){
    if (!t){
    t=creat();
    t->c=x;
    return t;
    }
    else if (t->c>x){
    t->lchild=insert(t->lchild,x);
    }
    else if (t->c<x){
    t->rchild=insert(t->rchild,x);
    }
    return t;
    }
     
    int main(){
    int n;
    while (cin>>n){
    loc=0;
    int x;
    node *t=NULL;
    while(n--){
    cin>>x;
    t=insert(t,x);//insert函数有返回值,一定要写t=intsert(),不要只写insert。
    }
    pre(t); cout<<endl;
    mid(t);cout<<endl;
    post(t); cout<<endl;
    }
     
    return 0;
    }
     
    node *t=null;只是建立了一个空指针,并不是建立了一个节点。建立节点在insert函数里面,引用了creat函数。
    二叉树的建立原理:先建立了一个110大小的节点数组,然后creat函数只是返回指向每个数组元素的指针,形成了树。
    loc要定义为全局变量,应为creat函数里面用到了loc。而不只是主函数里面用了loc
  • 相关阅读:
    Java进阶——带你入门分布式中的Nginx
    详细介绍Spring Boot 2.0的那些新特性与增强
    Kafka对Java程序员有多重要?连阿里都再用它处理亿万级数据统计
    C#面向对象的三大特性
    汽车租赁系统 封装。继承和多态
    深入C#数据类型小部分第二章
    Java面向对象的三大特征
    SQL Server 存储过程
    一篇文章教你学会基础的HTML
    初步了解Entity Framework
  • 原文地址:https://www.cnblogs.com/yexiaoqi/p/7221980.html
Copyright © 2011-2022 走看看