codevs 3143 二叉树的序遍历

来源:互联网 发布:广西驰程网络办公系统 编辑:程序博客网 时间:2024/06/07 18:28

地址:http://codevs.cn/problem/3143/


题目规定了树的每个位置的编号,所以可以直接用这个编号来遍历。


#include <iostream>using namespace std;int tree[200][2];void preorder(int i) {if(tree[i][0] != 0) {cout << tree[i][0] << " ";preorder(tree[i][0]);}if(tree[i][1] != 0) {cout << tree[i][1] << " ";preorder(tree[i][1]);}}void inorder(int i) {if(tree[i][0] != 0) {inorder(tree[i][0]);}cout << i << " ";if(tree[i][1] != 0) {inorder(tree[i][1]);}}void postorder(int i) {if(tree[i][0] != 0) {postorder(tree[i][0]);cout << tree[i][0] << " ";}if(tree[i][1] != 0) {postorder(tree[i][1]);cout << tree[i][1] << " ";}}int main() {int n;cin >> n;tree[0][0] = 1;for(int i = 1; i <= n; i++) {cin >> tree[i][0] >> tree[i][1];}preorder(0);cout << endl;inorder(1);cout << endl;postorder(0);return 0;}


0 0
原创粉丝点击