面试题 04.03. 特定深度节点链表
思路:层次遍历
/**
* 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<ListNode*> res;
if(tree==NULL) return res;
queue<TreeNode*> q;
q.push(tree);
while(!q.empty()){
int size = q.size();
ListNode* tmp = new ListNode(0);
ListNode* Lnow = tmp;
for(int i=0;i<size;i++){
TreeNode* now = q.front();
Lnow->next = new ListNode(now->val);
Lnow = Lnow->next;
q.pop();
if(now->left) q.push(now->left);
if(now->right) q.push(now->right);
}
if(tmp->next)
res.push_back(tmp->next);
}
return res;
}
};