1. 程式人生 > >L3-010. 是否完全二叉搜尋樹

L3-010. 是否完全二叉搜尋樹

#include <iostream>
#include <cstdio>
#include <queue>
#include <cstdlib>

using namespace std;

typedef struct node * Tree;
struct node{
  struct node * left,*right;
  int data;
  node(int a){
    left = NULL;
    right = NULL;
    data = a;
  }
};
int n;
Tree tree;
Tree insert(Tree tree,int a){
  if(tree == NULL){
    tree = new node(a);
  }
  else if(tree-> data < a){
    tree -> left = insert(tree -> left,a);
  }
  else{
    tree -> right = insert(tree -> right,a);
  }
  return tree;
}

void level(Tree tree){
  queue<node> q;
  q.push(*tree);
  int cnt = 0;
  while(!q.empty()){
    struct node temp = q.front();
    q.pop();
    
    if(cnt == n - 1){
      printf("%d\n",temp.data);
    }
    else{
      printf("%d ",temp.data);
    }
    cnt++;
    if(temp.left){
      q.push(*temp.left);
    }
    if(temp.right){
      q.push(*temp.right);
    }
    }
    
}
bool judge(Tree tree){
  queue<Tree> q;
  q.push(tree);
  int cnt = 0;
  while(!q.empty()){
    Tree temp = q.front();
    q.pop();
    if(temp == NULL){
      break;
    }
    cnt++;
    q.push(temp -> left);
    q.push(temp -> right);
    }
    //cout<<cnt<<endl;
    if(cnt == n){
      return true;
  }
  else{
    return false;
  }
}
int main(void){
  cin >> n;
  for(int i = 0; i < n; i++){
    int a;
    cin >> a;
    tree = insert(tree,a);
  }
  level(tree);
  int flag = judge(tree);
  if(flag){
    printf("YES\n");
  }
  else{
    printf("NO\n");
  }
  return 0;
}