特定深度节点链表
解题思路:BFS+链表
水题:基本BFS
用BFS一层一层遍历一遍,把同一层次的数存入同一个链表链表,最后输出结果即可
/** * 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*>vt; queue<TreeNode*>q; if(tree==NULL){ return vt; } q.push(tree); int len; while(!q.empty()){ ListNode* head=new ListNode(); ListNode* tail=new ListNode(); len=q.size(); for(int i=1;i<=len;i++){ TreeNode* newNode=q.front(); q.pop(); if(i==1){ head->val=newNode->val; tail = head; } else{ tail->next=new ListNode(newNode->val); tail=tail->next; } if(newNode->left){ q.push(newNode->left); } if(newNode->right){ q.push(newNode->right); } } vt.push_back(head); } return vt; } };