Input Specification:
Each input file contains one test case. For each case, the first line gives a positive integer N (≤10) which is the total number of nodes in the tree -- and hence the nodes are numbered from 0 to N−1. Then N lines follow, each corresponds to a node from 0 to N−1, and gives the indices of the left and right children of the node. If the child does not exist, a - will be put at the position. Any pair of children are separated by a space.
Output Specification:
For each test case, print in the first line the level-order, and then in the second line the in-order traversal sequences of the inverted tree. There must be exactly one space between any adjacent numbers, and no extra space at the end of the line.
Sample Input:
8
1 -
- -
0 -
2 7
- -
- -
5 -
4 6
Sample Output:
3 7 2 6 4 0 5 1
6 5 7 4 3 2 0 1
二叉树的静态写法:
struct node{
int val;
int left;
int right;
}
一般树的静态写法:
struct node{
int val;
vector<int> child;
}
树中的结点用一个node[]数组来盛放
#include<iostream>
#include<queue>
#include<vector>
using namespace std;
struct node{
int left = -1;
int right = -1;
};
node nodes[20];
int st[20];
queue<int> q;
vector<int> ans;
void inorder(int h){
if (h == -1) return;
inorder(nodes[h].right);
ans.push_back(h);
inorder(nodes[h].left);
}
void level(int h){
q.push(h);
while(!q.empty()){
int t = q.front();
q.pop();
ans.push_back(t);
if (nodes[t].right != -1) q.push(nodes[t].right);
if (nodes[t].left != -1) q.push(nodes[t].left);
}
}
int main(){
int n,head; char id1,id2;
cin>>n;
for (int i = 0; i < n; ++i){
cin>>id1>>id2;
if (id1 != '-') {
nodes[i].left = (id1 - '0');
st[id1 - '0'] ++;
}
if (id2 != '-'){
nodes[i].right = (id2 - '0');
st[id2 - '0'] ++;
}
}
for (int i = 0; i < n; ++i) // 寻找头结点
if (st[i] == 0){
head = i;
break;
}
level(head);
for (int i = 0; i < ans.size(); ++i){
if (i) cout<<" "<<ans[i];
else cout<<ans[i];
}
ans.clear();
cout<<endl;
inorder(head);
for (int i = 0; i < ans.size(); ++i){
if (i) cout<<" "<<ans[i];
else cout<<ans[i];
}
return 0;
}
本文详细介绍了二叉树的静态写法及遍历算法,包括先序、中序和后序遍历,重点讲解了如何通过层级遍历和中序遍历来获取二叉树的节点序列。同时,提供了完整的C++代码实现,帮助读者深入理解二叉树的遍历过程。
887

被折叠的 条评论
为什么被折叠?



