zoukankan      html  css  js  c++  java
  • 数据结构之二叉树 树结构练习——排序二叉树的中序遍历 (排序建树+中序遍历)

    树结构练习——排序二叉树的中序遍历

    Time Limit: 1000MS Memory limit: 65536K

    题目描述

    在树结构中,有一种特殊的二叉树叫做排序二叉树,直观的理解就是——(1).每个节点中包含有一个关键值 (2).任意一个节点的左子树(如果存在的话)的关键值小于该节点的关键值 (3).任意一个节点的右子树(如果存在的话)的关键值大于该节点的关键值。现给定一组数据,请你对这组数据按给定顺序建立一棵排序二叉树,并输出其中序 遍历的结果。
     

    输入

    输入包含多组数据,每组数据格式如下。
    第一行包含一个整数n,为关键值的个数,关键值用整数表示。(n<=1000)
    第二行包含n个整数,保证每个整数在int范围之内。

    输出

    为给定的数据建立排序二叉树,并输出其中序遍历结果,每个输出占一行。
     

    示例输入

    1
    2
    2
    1 20

    示例输出

    2
    1 20


    #include <iostream>
    #include <iomanip>
    #include <string>
    #include <string.h>
    #include <stdio.h>
    #include <algorithm>
    #include <queue>
    #include <vector>
    
    using namespace std;
    
    typedef struct node
    {
        int data;
        struct node *ll;
        struct node *rr;
    }Binode, *Bitree;
    
    void Creat_Sort_Bitree(Bitree &root, int key )
    {
        if(root==NULL)
        {
            root=new Binode;
            root->ll=NULL;
            root->rr=NULL;
            root->data=key;
            return ;
        }
        else
        {
            if(key < root->data)
            {
                Creat_Sort_Bitree(root->ll, key );
            }
            else
            {
                Creat_Sort_Bitree(root->rr, key );
            }
        }
    }
    
    int s[10000],e=0;
    
    void In_order(Bitree p)
    {
        if(p)
        {
            In_order(p->ll);
            s[e++]=p->data; //将该要被访问的数据 存进数组了。 一开始的时候写的直接输出, 但格式总是弄不对,只好放弃了那种写法!
            In_order(p->rr);
        }
    }
    
    int main()
    {
        int n, dd;
        int i;
        Bitree root;
        while(cin>>n)
        {
            root=NULL;
            for(i=0; i<n; i++)
            {
                cin>>dd;
                Creat_Sort_Bitree(root, dd );
            }
            e=0;
            In_order(root);
            for(i=0; i<e; i++)
            {
                if(i==0)
                  cout<<s[i];
                else
                  cout<<" "<<s[i];
            }
            cout<<endl;
        }
        return 0;
    }
    

       看到一篇博客里,一个人的中序访问数据的写法:

      

    void visit(BiTree T)
    {
    	if(T->data!=NULL)
    	{
    		if(f==1)
    		{
    			cout<<" "<<T->data;
    		}
    		else
    		{
    			cout<<T->data;
    			f=1;
    		}
    	}
    }
    
    void InOrder(BiTree T)
    {
    	if(T)
    	{
    		InOrder(T->lchild);
    		visit(T);
    		InOrder(T->rchild);
    	}
    }
    
  • 相关阅读:
    UOJ309 UNR #2 排兵布阵
    BZOJ4860: [Beijing2017]树的难题
    CQOI2017 部分题解
    SDOI2017 Round1 Day2 题解
    记SCOI2017
    BZOJ3810: [Coci2015]Stanovi
    BZOJ4785: [Zjoi2017]树状数组
    「ZJOI2007」「LuoguP1169」棋盘制作(并查集
    「LuoguP4147」 玉蟾宫(并查集
    「LuoguP1402」 酒店之王(最大流
  • 原文地址:https://www.cnblogs.com/yspworld/p/4120160.html
Copyright © 2011-2022 走看看