PAT A1064 Complete Binary Search Tree [complete binary search tree]

Title Description

Link
sequence to a series of configuration of the tree, the tree is fully known binary search tree, find its layer sequence preorder traversal of

analysis

  • Properties of the binary search tree: left subtree <Root <right subtree, and inorder traversal is LDR, therefore: the sequence preorder binary search tree is obtained in ascending order of the
  • Complete binary nature: storage order in the array is a sequence of the complete binary tree traversal sequence
  • Confuse the concept: To uniquely identify a binary tree, generally we need to have in order and in a sequence together. What does not exist in order to establish binary tree traversal. Well simply not unique. Here, however, since a completely define binary search tree, can be by inorder traversal of the array assignment.
  • The subject of the sorting sequence to give the sequence preorder. And in order traversal, in essence, the root access in accordance with LDR. We can change the operation of the access assignment \ (Nodes [the root] = A [++ len] \) , whereby the sequence stored in the array. Finally, the output of the sequence, i.e. sequence order of traversal.
  • Summary: Sort -> in order to traverse the transformation program, will become the access assignment -> get an array storage order -> get the sequence traversal sequence
  • Complete binary tree: the node is empty: \ (I> n-\) node is a leaf: \ (2i> n-\)
#include<bits/stdc++.h>
using namespace std;

const int maxn = 1e4+10;
int nodes[maxn];
int n,len;
int a[maxn];

void inorder(int root){
    if(root > n) return;
    inorder(2*root);
    nodes[root] = a[len++]; //将访问改成赋值
    inorder(2*root+1);
}

int main(){
    cin>>n;
    for(int i=0;i<n;i++) cin>>a[i];
    sort(a,a+n);
    inorder(1);
    for(int i=1;i<=n;i++){
        if(i==1) cout<<nodes[i];
        else cout<<" "<<nodes[i];
    }
    cout<<endl;

}

Guess you like

Origin www.cnblogs.com/doragd/p/11280181.html