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

 

 posted on 2013-08-07 15:38  xuanxu  阅读(169)  评论(0编辑  收藏  举报