您的位置:首页 > 其它

Q4.4 每一层的所有结点构建为一个链表

2013-08-07 15:38 239 查看
Given a binary search tree, design an algorithm which creates a linked list of all the nodes at each depth (i.e., if you have a tree with depth D, you’ll have D linked lists).

#include <list>

typedef struct Node
{
int val;
Node *left,*right;
}

vector<list<Node*>> findLevelList(Node *root)
{    int level = 0;
vector<list<Node*>>     res;
list<Node*> aList;
aList.push_back(root);
res.push_back();

while(!res[level].empty())
{    list<Node*> li;
list<Node*>::iterator itr;
for(itr = res[level].begin;
itr!=res[level].end();itr++)
{    Node *n = *itr;
if(n->left) li.push_back(n->left);
if(n->right)li.push_back(n->right);
}
++level;
res.push_back(li);
}
return res;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐