• PAT 1064. Complete Binary Search Tree


    A Binary Search Tree (BST) is recursively defined as a binary tree which has the following properties:

    • The left subtree of a node contains only nodes with keys less than the node's key.
    • The right subtree of a node contains only nodes with keys greater than or equal to the node's key.
    • Both the left and right subtrees must also be binary search trees.

    A Complete Binary Tree (CBT) is a tree that is completely filled, with the possible exception of the bottom level, which is filled from left to right.

    Now given a sequence of distinct non-negative integer keys, a unique BST can be constructed if it is required that the tree must also be a CBT. You are supposed to output the level order traversal sequence of this BST.

    Input Specification:

    Each input file contains one test case. For each case, the first line contains a positive integer N (<=1000). Then N distinct non-negative integer keys are given in the next line. All the numbers in a line are separated by a space and are no greater than 2000.

    Output Specification:

    For each test case, print in one line the level order traversal sequence of the corresponding complete binary search tree. All the numbers in a line must be separated by a space, and there must be no extra space at the end of the line.

    Sample Input:

    10
    1 2 3 4 5 6 7 8 9 0
    

    Sample Output:
    6 3 8 1 5 7 9 0 2 4

    分析

    首先这是一个二叉搜索树,它的中序遍历结果时一个非递减的数列,并且又是个完全二叉树,就如果用数组去储存的话,已知父节点下标为s的话,左孩子的下标为2*s+1,右孩子的下标为2*s+2,并且输出的格式是层级输出,即一层一层的从左到右输出。这道题相当于已知中序遍历的结果(给的数组从小到大排序)了,让你输出层级输出的结果。
    因为一旦完全二叉搜素树确定了,由于它的特定结构,它的层级输出的顺序也就确定了,关系是一一对应的,只需对0~n-1也中序遍历一遍,并和完全二叉树的中序遍历结果一一对应,再输出即可。
    
    #include<iostream>
    #include<algorithm>
    using namespace std;
    int a[1001],res[1001],tag=0;
    void inorder_traversal(int s,int n){
         if(2*s+1<n) pre(2*s+1,n);
         res[s]=a[tag++];
         if(2*s+2<n) pre(2*s+2,n);
    }
    int main(){
    	int n;
    	cin>>n;
    	for(int i=0;i<n;i++)
    		cin>>a[i];
    	sort(a,a+n);
    	inorder_traversal(0,n);
    	for(int i=0;i<n;i++)
    	    i>0?cout<<" "<<res[i]:cout<<res[i];
    	return 0;
    }
    
  • 相关阅读:
    利用python爬虫关键词批量下载高清大图
    多源最短路径算法—Floyd算法
    Dijkstra算法详细(单源最短路径算法)
    写博客没高质量配图?python爬虫教你绕过限制一键搜索下载图虫创意图片!
    并查集(不相交集合)详解与java实现
    AVL树(二叉平衡树)详解与实现
    二叉树——前序遍历、中序遍历、后序遍历、层序遍历详解(递归非递归)
    CSS基础总结
    HTML基础总结
    JavaSE 软件工程师 认证考试试卷3
  • 原文地址:https://www.cnblogs.com/A-Little-Nut/p/8366481.html
Copyright © 2020-2023  润新知