/**
* 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) {
if(!tree){
return{};
}
ListNode temp(0),*p = nullptr;
vector<ListNode*>result;
deque<TreeNode*>q;//deque支持高效插入和删除容器的头部元素,因此也叫做双端队列
q.push_back(tree);//push_back函数将一个新的元素加到vector的最后面,位置为当前最后一个元素的下一个元素
while(q.size()){
auto loops = q.size();
p = &temp;
while(loops--){
tree = q.front(),q.pop_front();//删除q中的第一个元素
p = p->next = new ListNode(tree->val);
if(tree->left){
q.push_back(tree->left);
}
if(tree->right){
q.push_back(tree->right);
}
}
result.push_back(temp.next);
}
return result;
}
};
10-11
154
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)