解题思路:
注意事项:
参考代码:
#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语言训练-求函数值 (C语言代码)浏览:924 |
C语言训练-计算1~N之间所有奇数之和 (C语言代码)浏览:725 |
【回文数(二)】 (C语言代码)浏览:881 |
汽水瓶 (C语言代码)浏览:612 |
C语言程序设计教程(第三版)课后习题7.3 (C语言代码)浏览:627 |
C语言程序设计教程(第三版)课后习题8.3 (C语言代码)浏览:428 |
哥德巴赫曾猜测 (C语言代码)浏览:1040 |
C语言程序设计教程(第三版)课后习题5.7 (C语言代码)浏览:604 |
C语言程序设计教程(第三版)课后习题6.10 (C语言代码)浏览:572 |
C语言程序设计教程(第三版)课后习题6.5 (C++代码)浏览:461 |