sicily Level Traversal of Bianry Trees

要求如下图:


按层次遍历返回所有节点的编号及数值。题中给出了一个list用于存放节点的编号及数值,我使用了一个queue用来层次遍历所有的节点。方法和之前的一样,在queue类型数据结构tree_to_record不为空的情况下,将根压入queue中,然后判断若其左右节点不为空,则将左右节点压入queue中,然后将tree_to_record的头元素tree_to_record.front()和它的编号存到list中,并在queue中将其pop掉。然后依次完成循环即可。注意return只需返回list即可,之前想得太多了!

代码如下:

#include<iostream>
#include<list>
#include<queue>
using namespace std;
typedef int T;
struct BinaryNode{
  T data;
  BinaryNode *left, *right;
  BinaryNode(T d, BinaryNode *l=NULL, BinaryNode* r=NULL):data(d), left(l), right(r) {};
};

list<pair<int, T> > levelTraverse(BinaryNode *root) {
	/*
	Returns a list of pairs of the form (p, v) when the tree root is traversed level by level, where v is the value on the node and  p is the order of the node during level traversal. For example, the result for the picture below is (1,20), (2, 40), (3, 50), (4, 30), (5, 10).  If the tree is empty, returns an empty list.
	*/
    int   num_to_count = 1;
	queue<BinaryNode*>tree_to_record;
	list<pair<int, T> > tree;
	T elem;
	if (root == NULL)
      return list<pair<int, T> >();
	tree_to_record.push(root);
	while (!tree_to_record.empty()) {
		if (tree_to_record.front()->left != NULL) {
			tree_to_record.push(tree_to_record.front()->left);
		}
		if (tree_to_record.front()->right != NULL) {
			tree_to_record.push(tree_to_record.front()->right);
		}
		elem = tree_to_record.front()->data;
		tree.push_back(pair<int, T>(num_to_count, elem));
		num_to_count++;
		tree_to_record.pop();
	}
	return tree;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值