Leetcode_刷题(特定深度节点链表)

80 阅读1分钟

刚刚又刷了一题,趁热打铁

题目是

给定一棵二叉树,设计一个算法,创建含有某一深度上所有节点的链表(比如,若一棵树的深度为 D,则会创建出 D 个链表)。返回一个包含所有深度的链表的数组。 示例: 输入:[1,2,3,4,5,null,7,8] 1 / \ 2 3 / \ \ 4 5 7 / 8 输出:[[1],[2,3],[4,5,7],[8]]

class Solution {public:    vector<ListNode*> listOfDepth(TreeNode* tree) {        queue<TreeNode*> q;        auto ans=vector<ListNode*>();        if(!tree) return ans;        q.push(tree);        while(!q.empty())        {        TreeNode* node;        int size=q.size();        auto ans1=new ListNode();        ListNode* temp=ans1;        for(int i=0;i<size;i++)        {            node=q.front();            q.pop();            if(node->left) q.push(node->left);            if(node->right) q.push(node->right);            temp->next=new ListNode(node->val);            temp=temp->next;        }                 ans.push_back(ans1->next);                   }    return ans;    }};

这是最后提交的代码

其中,一开始报错的最多是类型

auto sth="type"();

new ListNode相当于ListNode*,也就是节点,树的节点直接ListNode*,链表需要new;

然后就是next,返回链表的节点,需要sth->next;