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;
    }
};

猜你喜欢

转载自www.cnblogs.com/zzw-/p/13369012.html