Lintcode 242. 将二叉树按照层级转化为链表
题目描述:给一棵二叉树,设计一个算法为每一层的节点建立一个链表。也就是说,如果一棵二叉树有 D 层,那么你需要创建 D 条链表。
代码实现的时候,利用BFS在对二叉树每层遍历时直接转化为链表,也可以先将层级遍历存到vector中,最后再转化为链表放到结果result里面。
/**
* Definition of TreeNode:
* class TreeNode {
* public:
* int val;
* TreeNode *left, *right;
* TreeNode(int val) {
* this->val = val;
* this->left = this->right = NULL;
* }
* }
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
/**
* @param root the root of binary tree
* @return a lists of linked list
*/
vector<ListNode*> binaryTreeToLists(TreeNode* root) {
vector<ListNode*> result;
if (nullptr == root) {
return result;
}
queue<TreeNode*> nodeQueue;
nodeQueue.push(root);
//BFS进行层级遍历并转化为链表
while(!nodeQueue.empty()) {
ListNode* dummy = new ListNode;//每一层新建一个链表
ListNode* &levelList = dummy->next;//记住链表的初始节点,用于返回结果
int queueSize = nodeQueue.size();
for (int i = 0; i < queueSize; ++i) {
//对每层遍历时直接转化为链表,也可以先将层级遍历存到vector中,最后再转化为链表
ListNode* tmpList = new ListNode;
TreeNode* node = nodeQueue.front();
tmpList->val = node->val;
dummy->next = tmpList;
dummy = dummy->next;//链表移动
nodeQueue.pop();
if (nullptr != node->left) {
nodeQueue.push(node->left);
}
if (nullptr != node->right) {
nodeQueue.push(node->right);
}
}
result.push_back(levelList);
}
return result;
}
};