解题思路:
注意事项:
参考代码:
#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语言程序设计教程(第三版)课后习题7.1 (C++代码)浏览:717 |
采药 (C++代码)浏览:1322 |
【计算球体积】 (C语言代码)浏览:1027 |
C语言程序设计教程(第三版)课后习题1.5 (C语言代码)浏览:683 |
2005年春浙江省计算机等级考试二级C 编程题(3) (C语言代码)浏览:409 |
弟弟的作业 (C++代码)浏览:1335 |
C语言训练-计算1977!* (C++代码)浏览:900 |
【回文数(二)】 (C语言代码)浏览:793 |
C语言程序设计教程(第三版)课后习题6.1 (C语言代码)浏览:692 |
C语言程序设计教程(第三版)课后习题5.4 (C语言代码)浏览:934 |