1. 程式人生 > 實用技巧 >LeetCode 面試題04.03 特定深度節點連結串列

LeetCode 面試題04.03 特定深度節點連結串列

題目描述連結:https://leetcode-cn.com/problems/list-of-depth-lcci/

解題思路:採用廣度優先搜尋,進行層次遍歷,每層訪問時將每層的節點新增到相應層對應的連結串列當中,訪問完一層將該層的連結串列放到答案陣列中。

具體LeetCode參考程式碼如下:

/**
 * 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) { queue<TreeNode*>q; q.push(tree); vector
<ListNode*>res; TreeNode *p; int len; while(!q.empty()){ len=q.size(); ListNode *root=new ListNode(0); ListNode *temp; temp=root; for(int i=0;i<len;++i){ p=q.front(); q.pop();
if(p->left){ q.push(p->left); } if(p->right){ q.push(p->right); } ListNode *temp2=new ListNode(p->val); temp->next=temp2; temp=temp2; } res.push_back(root->next); } return res; } };