2 years ago

#42948

test-img

Amit khurrana

Convert Binary tree into linked list

Basically in this code, I am trying to make the individual linked list for each level of binary tree and store the address of each one in a vector, but when I am trying to print all the linked lists, it's not showing anything, can anyone tell me what I did wrong in this code.

void printLL(Node *head ){
    Node *temp = head ;
    while( temp!= NULL ){
        cout << temp->data << "  " ;
        temp = temp->next ;
    }
}

void treeToLL(BinaryTreeNode<int>* root){
    queue<BinaryTreeNode<int>*> qu;
    qu.push(root);
    qu.push(NULL);
    vector<Node*> vec ;
    Node * head = NULL;
    Node * tail = NULL;
    cout << vec.size();
    BinaryTreeNode<int> *front = NULL;
    while ( qu.size() > 1 )
    {
        front = qu.front();
        qu.pop();
        if( front == NULL){
            qu.push(NULL);
            vec.push_back(head);
            head = NULL;
            tail = NULL;
        }
        else{
            if (front->leftChild) qu.push(front->leftChild);
            if (front->rightChild) qu.push(front->rightChild);
            Node * LL = new Node(front->data);
            if( head == NULL) head == LL , tail == LL;
            tail ->next = LL;
            tail = tail->next;
        }
    }
    cout << vec.size();
    for(int i = 1 ; i <= vec.size(); i++){
        Node * temp = vec[i];
        printLL(temp);
        cout << endl;
    }
}

int main(){
    // 1 2 3 4 5 6 7 -1 -1 -1 -1 -1 -1 -1 -1
    BinaryTreeNode<int>* root = takeInputTree();
    printBinaryTree(root);
    treeToLL(root);
    return 0;
}

c++

linked-list

c++17

binary-tree

stdvector

0 Answers

Your Answer

Accepted video resources