L3-010. 是否完全二叉搜索树
https://www.patest.cn/contests/gplt/L3-010
L3-010. 是否完全二叉搜索树
时间限制
400 ms
内存限制
65536 kB
代码长度限制
8000 B
判题程序
Standard
作者
陈越
将一系列给定数字顺序插入一个初始为空的二叉搜索树(定义为左子树键值大,右子树键值小),你需要判断最后的树是否一棵完全二叉树,并且给出其层序遍历的结果。
输入格式:
输入第一行给出一个不超过20的正整数N;第二行给出N个互不相同的正整数,其间以空格分隔。
输出格式:
将输入的N个正整数顺序插入一个初始为空的二叉搜索树。在第一行中输出结果树的层序遍历结果,数字间以1个空格分隔,行的首尾不得有多余空格。第二行输出“YES”,如果该树是完全二叉树;否则输出“NO”。
输入样例1:9 38 45 42 24 58 30 67 12 51输出样例1:
38 45 24 58 42 30 12 67 51 YES输入样例2:
8 38 24 12 45 58 67 42 51输出样例2:
38 45 24 58 42 12 67 51 NO
分析:
1.根据规则(左大右小),建立二叉搜索树
2.层次遍历输出
3.判断是否为完全二叉树
1、2为基本树操作,3应用完全二叉树性质(在进行层次遍历时,记录每个结点的位置,有节点位置id大于n,不是完全二叉树)
模型:
struct node { int x; int id; node *l,*r; };
#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> #include <cmath> #include <queue> #include <stack> #include <vector> using namespace std; struct node { int x; int id; node *l,*r; }; int n; int flag; void build(node *&head,int x) { if(!head)//head==NULL,新建节点 { head=new node; head->l=head->r=NULL; head->x=x; return ; } if(x>head->x) build(head->l,x); else build(head->r,x); } void LevelOrder(node *&head) { queue<node*>Q; head->id=1; Q.push(head); node *tmp; int first=1; while(!Q.empty()) { tmp=Q.front(),Q.pop(); if(tmp->id>n) flag=1; if(first) first=0; else printf(" "); printf("%d",tmp->x); if(tmp->l) Q.push(tmp->l),tmp->l->id=tmp->id<<1;//相当于*2 if(tmp->r) Q.push(tmp->r), tmp->r->id=tmp->id<<1|1;//相当于*2+1 } printf("\n"); } int main() { node *head; int x; while(cin>>n) { head=NULL; flag=0; for(int i=0;i<n;i++) { scanf("%d",&x); build(head,x); } LevelOrder(head); if(flag) printf("NO\n"); else printf("YES\n"); } return 0; }
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
#include "iostream" #include "cstdio" #include "queue" using namespace std; struct BstNode{ int id; int data; BstNode *left,*right; }; bool flag=false; BstNode* GetNewNode(int data) { BstNode* newNode = new BstNode(); newNode->data = data; newNode->left = newNode->right = NULL; return newNode; } BstNode * Insert(BstNode * root,int data) { if(root == NULL) { root = GetNewNode(data); } else if(data > root->data) { root->left = Insert(root->left,data); } else { root->right = Insert(root->right,data); } return root; } void LevelOrder(BstNode *&root,int n) { queue<BstNode*>Q; while(!Q.empty())Q.pop(); root->id=1; Q.push(root); BstNode *tmp=root; int first=1; while(!Q.empty()){ tmp=Q.front(); if(tmp->id>n)flag=true; if(first==1){ printf("%d",tmp->data); first++; } else{ printf(" %d",tmp->data); } Q.pop(); if(tmp->left!=NULL){ Q.push(tmp->left);tmp->left->id=tmp->id<<1; } if(tmp->right!=NULL){ Q.push(tmp->right);tmp->right->id=tmp->id<<1|1; } } printf("\n"); } int main() { int n,x; while(~scanf("%d",&n)){ BstNode * root=NULL; for(int i=0;i<n;i++){ scanf("%d",&x); root=Insert(root,x); } flag=false; LevelOrder(root,n); if(flag) printf("NO\n"); else printf("YES\n"); } return 0; }