/**
* 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==nullptr)return res;
queue<TreeNode*>q;
q.push(tree);
while(!q.empty()){
ListNode *head=nullptr;
ListNode *prev=nullptr;
int currsize=q.size();
for(int i=0;i<currsize;i++){
TreeNode*currnode=q.front();//队列的探查函数是front()
ListNode*newnode=new ListNode(currnode->val);//这边是把树节点转化为链表结点。。
q.pop();
//注意建立链表首结点。
if(head==nullptr){
head=newnode;
}
else{
prev->next=newnode;
}
prev=newnode;//这一步看代码意思是指针往后靠。。
if(currnode->left!=nullptr){
q.push(currnode->left);
}
if(currnode->right!=nullptr){
q.push(currnode->right);
}
}
res.push_back(head);
}
return res;
}
};
面试题 04.03. 特定深度节点链表
最新推荐文章于 2024-06-12 14:12:19 发布