/*
简单的二叉树前序遍历,将节点封装好按照id存入数组即可
遍历之前需要找到根节点,可以像这样子做个父节点数组,也可以在输入时就推算根节点
*/
/*
Run Time: 0secs
Run Memory: 332KB
*/
#include <iostream>
#include <memory.h> //memset初始化
using namespace std;
typedef struct Point{
int id; //当前节点id (1-1000)
char word; //该节点存储的字符 (A-Z)
int left; //左子树,为0则无
int right; //右子树,为0则无
};
Point tree[1001];
int parent[1001];
//得到树根
int findRoot(int root){
while(1){
if(parent[root] != 0){ //如果不是0,则说明他还有老爸
root = parent[root];
}else{ //如果他就是0,则说明他就是元老
return root;
}
}
}
void preOrder(int root){
Point node = tree[root];
cout << node.word;
if(node.left != 0)
preOrder(node.left);
if(node.right != 0)
preOrder(node.right);
}
int main()
{
int N;
int root;
while (cin>>N && N){
memset(parent, 0, sizeof(int)*1001);
for(int i=0; i<N; i++){
Point buf;
cin >> buf.id >> buf.word >> buf.left >> buf.right;
tree[buf.id] = buf;
parent[buf.left] = buf.id;
parent[buf.right] = buf.id;
root = buf.id;
}
root = findRoot(root);
preOrder(root);
cout << endl;
}
return 0;
}
Sicily 1156. Binary tree
最新推荐文章于 2016-12-06 10:34:01 发布