sicily Level Traversal of Bianry Trees

来源:互联网 发布:网络银行存在的问题 编辑:程序博客网 时间:2024/06/05 16:58

要求如下图:


按层次遍历返回所有节点的编号及数值。题中给出了一个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;}


0 0