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).
Have you met this question in a real interview?
Yes
Example
Given binary tree:
1
/ \
2 3
/
4
return
[
1-
>
null,
2-
>
3-
>
null,
4-
>
null
]
/**
* 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) {
// Write your code here
vector<ListNode*> results;
if (root == NULL) {
return results;
}
queue<TreeNode*> q;
q.push(root);
while (!q.empty()) {
int size = q.size();
ListNode head(0);
ListNode* pre = &head;
for (int i = 0; i < size; ++i) {
TreeNode* cur = q.front(); q.pop();
pre->next = new ListNode(cur->val);
pre = pre->next;
if (cur->left) {
q.push(cur->left);
}
if (cur->right) {
q.push(cur->right);
}
}
results.push_back(head.next);
}
return results;
}
};