• [二叉查找树] 二叉排序树


    题目描述

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

    输入

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

    输出

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

    样例输入

    1 2 2 8 15 4 21 10 5 39

    样例输出

    2 2 2 8 15 8 15 15 8 21 10 5 39 5 10 21 39 5 10 39 21

    分析:题目涉及到了二叉查找树的建立,先序遍历,中序遍历,后序遍历。其中,二叉查找树的建立是在普通二叉树建立的基础上简单扩展来的,较为简单。此处的先、中、后序遍历与普通二叉树的相同。

    #include <iostream>
    #include <cstdio>
    #include <cmath>
    #include <cstring>
    #include <algorithm>
    #include <vector>
    #include <cmath>
    #include <queue>
    using namespace std;
    
    struct node
    {
        int data;
        node * lchild,*rchild;
    };
    
    void insert(node * & root,int data)
    {
        if(root==NULL)
        {
            root=new node;
            root->data=data;
            root->lchild=NULL;
            root->rchild=NULL;
            return ;
        }
        if(data==root->data)
        {
            return ;
        }
        else if(data<root->data)
        {
            insert(root->lchild,data);
        }
        else
        {
            insert(root->rchild,data);
        }
    }
    
    void preOrder(node * root)
    {
        if(root!=NULL)
        {
            cout<<root->data<<" ";
            preOrder(root->lchild);
            preOrder(root->rchild);
        }
    }
    
    void inOrder(node * root)
    {
        if(root!=NULL)
        {
            inOrder(root->lchild);
            cout<<root->data<<" ";
            inOrder(root->rchild);
        }
    }
    
    void postOrder(node * root)
    {
        if(root!=NULL)
        {
            postOrder(root->lchild);
            postOrder(root->rchild);
            cout<<root->data<<" ";
        }
    }
    
    int main()
    {
        int n;
        while(cin>>n)
        {
            node * root=NULL;
            for(int i=0;i<n;i++)
            {
                int a;
                cin>>a;
                insert(root,a);
            }
            preOrder(root);
            cout<<endl;
            inOrder(root);
            cout<<endl;
            postOrder(root);
            cout<<endl;
        }
    }
  • 相关阅读:
    LeetCode算法题-Reverse String II(Java实现)
    LeetCode算法题-Convert BST to Greater Tree(Java实现)
    LeetCode算法题-K-diff Pairs in an Array(Java实现)
    LeetCode算法题-Minimum Absolute Difference in BST(Java实现)
    基于Bootstrap和Knockout.js的ASP.NET MVC开发实战 关于 拦截器的 学习 部分
    基于bootstrap和knockoutjs使用 mvc 查询
    Kindle Unlimited 上线的最热书单
    基于Bootstrap和Knockout.js的ASP.NET MVC开发实战
    程序员的数学
    数学女孩
  • 原文地址:https://www.cnblogs.com/xiongmao-cpp/p/6431223.html
Copyright © 2020-2023  润新知