题目链接:https://leetcode-cn.com/problems/list-of-depth-lcci/
一年半没有写广搜了,重新上手的第一道题还一次过了就很nice
由于要不同深度分类,所以抛开传统的while(!q.empty()),还需要在里面每次计算q.size(),作为这一层的操作次数。
由于每次要把当前遍历节点的左右子树继续push到队列中,所以队列要用TreeNode*型,不然只存int型的值不好判断左右子树。
代码如下:
/**
* 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* root) {
vector<ListNode*> res;
if(root == NULL) {
return res;
}
queue<TreeNode*> q;
q.push(root);
while(!q.empty()) {
int len = q.size();
ListNode* pos = new ListNode(0);
ListNode* rsv = pos;
while(len--) {
TreeNode* now = q.front();
q.pop();
ListNode* nxt = new ListNode(now->val);
pos->next = nxt;
pos = pos->next;
if(now->left) {
q.push(now->left);
}
if(now->right) {
q.push(now->right);
}
}
res.push_back(rsv->next);
}
return res;
}
};