/*1156. Binary tree
题目大意:给出几个字符串,包含有节点的id,节点内容、左儿子id,右儿子id
如
4 C 1 3
1 A 0 0
3 B 0 0
求出此构成的二叉树后的先序遍历结果
解题思路:简历一个map<int,int>数组,key是节点的id,value是节点在数组中
下标。先遍历整个tree[n]的节点,找出根节点的下标。找出那个没有
出现在任意一个节点的儿子id中的节点id即是根节点。
然后调用preOrder函数进行先序遍历。
*/
#include <iostream>
#include <stdlib.h>
#include <algorithm>
#include <map>
using namespace std;
struct node
{
int identifier;
int left;
int right;
char content;
};
node *tree;
map<int,int> m;
void preOrder(int index)
{
if(index == 0)
{
return;
}
cout << tree[index].content;
preOrder(m[tree[index].left]);
preOrder(m[tree[index].right]);
}
int main()
{
int n;
int id, left, right;
char content;
while(cin>> n)
{
tree = new node[n+1];
m.clear();
for(int i=1; i<=n; i++)
{
cin >> id >> content >> left >> right;
node temp ={id,left, right, content};
m[id] = i;
tree[i] = temp;
}
int rootID;
for(int i=1; i<=n; i++)
{
//cout << tree[i].identifier << " " << tree[i].content << " " << tree[i].left << " " << tree[i].right << endl;
rootID = i;
bool isRoot = true;
for(int j=1; j<=n; j++)
{
if(tree[i].identifier == tree[j].left || tree[i].identifier == tree[j].right)
{
isRoot = false;
break;
}
else
continue;
}
if(isRoot)
break;
}
//cout << m[tree[rootID].identifier] << endl;
preOrder( rootID );
cout << endl;
delete[] tree;
}
system("pause");
return 0;
}
1156.Binary Tree(先求出根,在进行树遍历)
最新推荐文章于 2022-04-02 15:04:45 发布