1156.Binary Tree(先求出根,在进行树遍历)

/*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;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值