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 << "请输入要创建的二叉树的结点数: "; } }
相关文章推荐
- homework-06
- BZOJ_4320_ShangHai2006 Homework_分块
- sicily 数据结构 1014. Translation
- mdss 8x26/8x74 display debug and reading notes(vsync, interface and so on)
- Sicily 1014. Specialized Four-Dig
- Homework-09 二维数组动态显示
- Sicily2015
- homework-10
- Sicily课程练习 1007. Bracket Matching
- Google Code Jam Notes - Rotate - Java
- Sicily 1150. 简单魔板 解题报告
- Clean Code Study Notes 2
- sicily. 1815 计算两点间的距离
- sicily 1091.Maximum Sum
- sicily 后缀表达式计算
- sicily 1154. Easy sort (tree sort& merge sort)
- Exception and Interrupts Notes of 80386 Programmer manual
- udacity-web development-homework(unit2-rot13)
- Sicily 1930
- Doing Homework again