LeetCode-[list-of-depth-lcci]
特定深度节点链表-求解每一层二叉树从左到右遍历形成的链表
list-of-depth-lcci
- 这是关于二叉树的问题,遍历每一层的结点并且存在链表中。
- 可以采取队列类似于广度优先搜索的方法进行搜索。每次出队列时,首先记录队列中还有多少个同一层的结点,再遍历所有这些结点并且将左右结点再次进栈。
#include<iostream>
#include<cstring>
#include<string>
#include<algorithm>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
// 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*> list;
queue<TreeNode*> que;
TreeNode* node=NULL;
que.push(tree);
while(!que.empty()){
ListNode* head=new ListNode(-1);
ListNode* temp=head;
int ans=que.size();
for(int i=0;i<ans;i++){
node=que.front();
temp->next=new ListNode(node->val);
que.pop();
temp=temp->next;
if(node->left){
que.push(node->left);
}
if(node->right){
que.push(node->right);
}
}
list.push_back(head->next);
}
return list;
}
};
//输入:[1,2,3,4,5,null,7,8]
// 1
// / \
// 2 3
// / \ \
// 4 5 7
// /
// 8
int main(){
TreeNode* t1=new TreeNode(1);
TreeNode* t2=new TreeNode(2);
TreeNode* t3=new TreeNode(3);
TreeNode* t4=new TreeNode(4);
TreeNode* t5=new TreeNode(5);
TreeNode* t7=new TreeNode(7);
TreeNode* t8=new TreeNode(8);
t4->left=t8;
t2->left=t4;t2->right=t5;
t3->right=t7;
t1->left=t2;t1->right=t3;
Solution solution;
vector<ListNode*> vec=solution.listOfDepth(t1);
for(int i=0;i<vec.size();i++){
ListNode* list=vec[i];
while(list){
cout<<list->val<<" ";
list=list->next;
}
cout<<endl;
}
system("pause");
return 0;
}
Either Excellent or Rusty