题目概述
原题链接
树及链表定义如下:
/**
* 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) {}
* };
思考过程
- 本题即为二叉树层序遍历的一个变体,只是将返回由
vector<vector<int>>
变为vector<ListNode*>
- 层序遍历使用
queue
或者stack
均可实现,个人习惯使用queue
- 需要注意链表的操作,及时更新到下一个节点以及根据函数定义进行初始化(这点与简单的二叉树层序遍历存在差异)
实现代码
class Solution {
public:
vector<ListNode*> listOfDepth(TreeNode* tree) {
// 考虑特殊情况
vector<ListNode*> ans;
if (tree == NULL) return ans;
queue<TreeNode*> q;
q.push(tree);
// 创建指向链表head的前一个节点
ListNode* head = new ListNode(0);
while(!q.empty()) {
int level = q.size();
// 创建一个临时指针用于操作
ListNode* cur = head;
while(level > 0) {
TreeNode* temp = q.front();
// 链表创建及指针移动操作
cur->next = new ListNode(temp->val);
cur = cur->next;
// 此处就和普通二叉树层序遍历一致了
q.pop();
level--;
if (temp->left) q.push(temp->left);
if (temp->right) q.push(temp->right);
}
// 所以此处在添加元素时使用head->next而不是head
ans.push_back(head->next);
}
return ans;
}
};