您的位置:首页 > 其它

sicily_homeworkNotes

2016-10-27 19:15 281 查看

1、二叉树的遍历(simple)

将一组数前中序遍历输出

#include<iostream>

using namespace std;
struct node {
int data;
node *left;
node *right;
node(int temp) {
left = right = NULL;
data = temp;
}
};
void insert(node *root, int num) {
if (num <= root->data) {
if (root->left == NULL) {
root->left = new node(num);
} else {
insert(root->left, num);
}
} else {
if (root->right == NULL) {
root->right = new node(num);
} else {
insert(root->right, num);
}
}
}
void inOrder(node *root) {
if (root != NULL) {
inOrder(root->left);
cout << root->data << " " ;
inOrder(root->right);
}
}
void preOrder(node *root) {
if (root != NULL) {
cout << root->data << " " ;
preOrder(root->left);
preOrder(root->right);
}
}

int main() {
int n;
while(cin >> n && n != 0) {
int num;
cin >> num;
node *root;
root = new node(num);
for (int i = 1; i < n; i++) {
cin >> num;
insert(root,num);
}

inOrder(root);
cout << endl;
preOrder(root);
cout << endl;

}
}


2、二叉树的简单倒置和显示

#include<iostream>

using namespace std;
struct node {
int data;
node *left;
node *right;
node(int temp) {
left = right = NULL;
data = temp;
}
};
void insert(node *root, int num) {
if (num <= root->data) {
if (root->left == NULL) {
root->left = new node(num);
} else {
insert(root->left, num);
}
} else {
if (root->right == NULL) {
root->right = new node(num);
} else {
insert(root->right, num);
}
}
}

void interchange(node *root) {
if (root != NULL) {
if (root->left != NULL || root->right != NULL) {
//交换左右子树
node * temp = root->left;
root->left = root->right;
root->right = temp;

if (root->left != NULL) {
interchange(root->left);
}
if (root->right != NULL) {
interchange(root->right);
}
}
}
}

void inOrder(node *root, int height) {
if (root != NULL) {
inOrder(root->left,height+1);
for (int i = 0; i < height; i++) {
cout << "\t";
}
cout << ">>"<<root->data<< endl;
inOrder(root->right, height+1);
} else {
return;
}
}

int main() {
int n;
cout << "请输入要创建的二叉树的结点数: ";
while(cin >> n && n != 0) {
int num;
cout <<"请输入创建的二叉树的具体结点的权值: "<<endl;
cin >> num;
node *root;
root = new node(num);
for (int i = 1; i < n; i++) {
cin >> num;
insert(root,num);
}
cout << "未进行处理的二叉树:(横向输出)"<<endl;
inOrder(root,0);
cout << "\n\n";
cout << endl;
interchange(root);
cout << "左右子树对换后的二叉树:(横向输出)"<<endl;
inOrder(root,0);
cout << "\n\n";
cout << endl;
cout << "请输入要创建的二叉树的结点数: ";
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  sicily 二叉树