面试题 特定深度节点链表
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
vector<ListNode*> listOfDepth(TreeNode* tree) {
//设置存入链表的vector容器中
vector<ListNode*> result;
int count = 1;//当前结点数
int nextcount = 0;//设置下一层结点数
queue<TreeNode*> queuece;//设置队列进行层序遍历
//开始层序遍历
queuece.push(tree);
int size = 1;
while(size != 0){
//设置每一层的链表的头节点
ListNode* p = NULL;
//指向每一条的链表
ListNode* tail = NULL;
for(int i = 0;i < count;i++){
TreeNode* temp = queuece.front();
//如果p为空,则给它赋头节点,如果不为空,则插入此链表的尾部
if(p == NULL){
p = new ListNode(temp->val);
tail = p;
}else{
ListNode* newnode = new ListNode(temp->val);
tail->next = newnode;
tail = newnode;
}
if(temp->left != NULL){
queuece.push(temp->left);
nextcount++;//更新下一层的结点数
size++;
}
if(temp->right != NULL){
queuece.push(temp->right);
nextcount++;//更新下一层的结点数
size++;
}
queuece.pop();
size--;
}
count = nextcount;//更新本层结点数
result.push_back(p);
nextcount = 0;
}
return result;
}
};