242. Convert Binary Tree to Linked Lists by Depth
/**
* 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 *> res;
if(root == NULL){
return res;
}
std::queue<TreeNode *> q;
q.push(root);
while(!q.empty()){
int sizeQ = q.size();
ListNode *dummy = new ListNode(0);
ListNode *copy = dummy;
for(int i = 0; i < sizeQ; i++){
TreeNode *tmp = q.front();
q.pop();
dummy->next = new ListNode(tmp->val);
dummy = dummy->next;
if(tmp->left){
q.push(tmp->left);
}
if(tmp->right){
q.push(tmp->right);
}
}
res.push_back(copy->next);
}
return res;
}
};
Comments
Post a Comment