标签:技术 先序 else 直接 不能 search nod child print
#include<bits/stdc++.h>
using namespace std;
struct node{
int data;
node *lchild, *rchild;
};
void insert(node* &root, int data){
if(root == NULL){
root = new node;
root->data = data;
root->lchild = root->rchild = NULL;//这句不能够漏掉
return;
}
if(data < root->data) insert(root->lchild, data);
else insert(root->rchild, data);
}
//先序遍历结果存于vi
void preOrder(node* root, vector<int> &vi){
if(root == NULL) return;
vi.push_back(root->data);
preOrder(root->lchild, vi);
preOrder(root->rchild, vi);
}
//镜像树的先序遍历,结果存放于vi
void preOrderMirror(node* root, vector<int> &vi){
if(root == NULL) return;
vi.push_back(root->data);
preOrderMirror(root->rchild, vi);
preOrderMirror(root->lchild, vi);
}
//后序遍历结果存于vi
void postOrder(node* root, vector<int> &vi){
if(root == NULL) return;
postOrder(root->lchild, vi);
postOrder(root->rchild, vi);
vi.push_back(root->data);
}
//镜像树的后序遍历,结果存放于vi
void postOrderMirror(node* root, vector<int> &vi){
if(root == NULL) return;
postOrderMirror(root->rchild, vi);
postOrderMirror(root->lchild, vi);
vi.push_back(root->data);
}
vector<int> origin, pre, preM, post, postM;
int main(){
int n, data;
node* root = NULL;
scanf("%d", &n);
for(int i = 0; i < n; i++){
scanf("%d", &data);
origin.push_back(data);
insert(root, data);
}
preOrder(root, pre);
preOrderMirror(root, preM);
postOrder(root, post);
postOrderMirror(root, postM);
if(origin == pre){
printf("YES\n");
for(int i = 0; i < n; i++){
if(i != 0) printf(" ");
printf("%d", post[i]);
}
}else if(origin == preM){
printf("YES\n");
for(int i = 0; i < n; i++){
if(i != 0) printf(" ");
printf("%d", postM[i]);
}
}else{
printf("NO\n");
}
return 0;
}
A1043 Is It a Binary Search Tree (25分)
标签:技术 先序 else 直接 不能 search nod child print
原文地址:https://www.cnblogs.com/tsruixi/p/12333745.html