- Convert Binary Tree to Linked Lists by Depth
中文English
Given a binary tree, design an algorithm which creates a linked list of all the nodes at each depth (e.g., if you have a tree with depth D, you’ll have D linked lists).
Example
Example 1:
Input:
{1,2,3,4}
1
/
2 3
/
4
Output:
[
1->null,
2->3->null,
4->null
]
Example 2:
Input:
{1,#,2,3}
1
2
/
3
Output:
[
1->null,
2->null,
3->null
]
解法1:BFS分层遍历
代码如下:
/**
* 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) {
if (!root) return vector<ListNode*>();
queue<TreeNode *> q;
vector<ListNode *> result;
ListNode * listNode;
q.push(root);
while(!q.empty()) {
int n = q.size();
ListNode * dummyHead = new ListNode(0);
listNode = dummyHead;
for (int i = 0; i < n; ++i) {
TreeNode * treeNode = q.front();
q.pop();
listNode->next = new ListNode(treeNode->val);
listNode = listNode->next;
if (treeNode->left) {
q.push(treeNode->left);
}
if (treeNode->right) {
q.push(treeNode->right);
}
}
listNode->next = NULL;
result.push_back(dummyHead->next);
}
return result;
}
};