3143 二叉樹的序遍歷codevs
阿新 • • 發佈:2017-11-18
後序 default des -h 遍歷 content names wrap pad
3143 二叉樹的序遍歷
時間限制: 1 s 空間限制: 32000 KB 題目等級 : 白銀 Silver 題目描述 Description
求一棵二叉樹的前序遍歷,中序遍歷和後序遍歷
輸入描述 Input Description第一行一個整數n,表示這棵樹的節點個數。
接下來n行每行2個整數L和R。第i行的兩個整數Li和Ri代表編號為i的節點的左兒子編號和右兒子編號。
輸出描述 Output Description輸出一共三行,分別為前序遍歷,中序遍歷和後序遍歷。編號之間用空格隔開。
樣例輸入 Sample Input5
2 3
4 5
0 0
0 0
0 0
樣例輸出 Sample Output1 2 4 5 3
4 2 5 1 3
4 5 2 3 1
數據範圍及提示 Data Size & Hintn <= 16
#include<iostream> using namespace std; int a[17][2]; int n; void F(int x) { cout << x << " "; if(a[x][0]) F(a[x][0]); if(a[x][1]) F(a[x][1]); }void M(int x) { if(a[x][0]) M(a[x][0]); cout << x << " "; if(a[x][1]) M(a[x][1]); } void B(int x) { if(a[x][0]) B(a[x][0]); if(a[x][1]) B(a[x][1]); cout << x << " "; } int main() { cin >> n; for(int i = 1; i <= n; i++) cin>> a[i][0] >> a[i][1]; F(1); cout << endl; M(1); cout << endl; B(1); cout << endl; }
3143 二叉樹的序遍歷codevs