题解 | #二叉排序树#

二叉排序树

http://www.nowcoder.com/questionTerminal/b42cfd38923c4b72bde19b795e78bcb3

#include<iostream>
#include<string>
using namespace std;

struct node{
  int data;
  node* leftch;
  node* rightch;
  node(int x):data(x),leftch(nullptr),rightch(nullptr){}
};

int preflag=0,inflag=0,postflag=0;

node* insert(int a,node* root){//插入(注意重复元素不插入)
  if(root==nullptr){
    root=new node(a);
    return root;
  }
  if(a>root->data){
    root->rightch=insert(a,root->rightch);
  }
  else if(a<root->data){
    root->leftch=insert(a,root->leftch);
  }
  return root;
}

void preorder(node* root){//先序
  if(root==nullptr)return;
  if(preflag==0){
    printf("%d",root->data);
    preflag++;
  }
  else printf(" %d",root->data);
  preorder(root->leftch);
  preorder(root->rightch);
}

void inorder(node* root){//中序
  if(root==nullptr)return;
  inorder(root->leftch);
  if(inflag==0){
    printf("%d",root->data);
    inflag++;
  }
  else printf(" %d",root->data);
  inorder(root->rightch);
}

void postorder(node* root){//后序
  if(root==nullptr)return;
  postorder(root->leftch);
  postorder(root->rightch);
  if(postflag==0){
    printf("%d",root->data);
    postflag++;
  }
  else printf(" %d",root->data);
}

int main(){
  int n;
  while(scanf("%d",&n)!=EOF){
    int x;
    preflag=inflag=postflag=0;
    node* root=nullptr;
    for(int i=0;i<n;i++){
      scanf("%d",&x);
      root=insert(x,root);
    }
    preorder(root);
    printf("\n");
    inorder(root);
    printf("\n");
    postorder(root);
    printf("\n");
  }
  
  return 0;
}

全部评论

相关推荐

千千倩倩:简历问题有点多,加v细聊
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务