解题思路:
注意事项:
参考代码:
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
struct tree{
int v;
tree *left=NULL,*right=NULL;
};
bool cmp(tree t1,tree t2){
return t1.v<t2.v;
}
void pre(tree *dot){
cout<<dot->v<<" ";
if(dot->left) pre(dot->left);
if(dot->right) pre(dot->right);
}
void mid(tree *dot){
if(dot->left) mid(dot->left);
cout<<dot->v<<" ";
if(dot->right) mid(dot->right);
}
void post(tree *dot){
if(dot->left) post(dot->left);
if(dot->right) post(dot->right);
cout<<dot->v<<" ";
}
void built(tree *root,tree *dot){
if(dot->v<root->v){
if(root->left) built(root->left,dot);
else root->left=dot;
}
else if(dot->v>root->v){
if(root->right) built(root->right,dot);
else root->right=dot;
}
}
int main(){
int n;
while(cin>>n){
vector<tree> vt;
for(int i=0;i<n;i++){
int put;
cin>>put;
tree *te = new tree;
te->v=put;
vt.push_back(*te);
}
//sort(vt.begin(),vt.end(),cmp);
// 假设根节点 为vt[0]
for(int i=1;i<vt.size();i++){
built(&vt[0],&vt[i]);
}
// 输出结果
pre(&vt[0]);
cout<<"\n";
mid(&vt[0]);
cout<<"\n";
post(&vt[0]);
cout<<"\n";
}
}
0.0分
0 人评分
C语言程序设计教程(第三版)课后习题8.4 (C语言代码)浏览:568 |
字符串对比 (C语言代码)浏览:1458 |
printf基础练习2 (有点不明白)浏览:876 |
母牛的故事 (C语言代码)浏览:1446 |
C语言程序设计教程(第三版)课后习题9.3 (C语言代码)浏览:2109 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:621 |
The 3n + 1 problem (C语言代码)浏览:541 |
敲七 (C语言代码)浏览:2741 |
数列问题 (C语言代码)浏览:1066 |
青年歌手大奖赛_评委会打分 (C语言代码)浏览:2232 |