[LeetCode]面试题 04.03. 特定深度节点链表

二叉树转换成链表

Posted by JinFei on November 15, 2021

题目描述

给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。

Example1:

输入:[1,2,3,4,5,null,7,8]

    1
   /  \ 
  2    3
 / \    \ 
4   5    7    /   8

输出:[[1],[2,3],[4,5,7],[8]]

Note:

  • n == points.length
  • 2 <= n <= 105
  • points[i].length == 2
  • 0 <= xi, yi <= 109

解题思路

/**
 * 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()){
            int size = q.size();
            ListNode* head = new ListNode(0);
            ListNode* p = head;
            for(int i = 0; i < size; i++){
                TreeNode* cur = q.front();
                q.pop();
                if(cur -> left){
                    q.push(cur -> left);
                }
                if(cur -> right){
                    q.push(cur -> right);
                }
                p -> next = new ListNode(cur -> val);
                p = p -> next;
            }
            res.push_back(head -> next);
        }
        return res;
    }
};