Find error in the following code:
Ques: Given a Binary Tree (BT), convert it to a Doubly Linked List(DLL) In-Place. The left and right pointers in nodes are to be used as previous and next pointers respectively in converted DLL. The order of nodes in DLL must be same as Inorder of the given Binary Tree. The first node of Inorder traversal (leftmost node in BT) must be the head node of the DLL.
Find error in the following code: #include <bits/stdc++.h>
using namespace std;
// Tree Node
struct Node
{
int data;
Node* left;
Node* right;
};
{
Node* temp = new Node;
temp->data = val;
temp->left = NULL;
temp->right = NULL;
return temp;
}
// Function to Build Tree
Node* buildTree(string str)
{
// Corner Case
if(str.length() == 0 || str[0] == 'N')
return NULL;
// Creating
// string after spliting by space
vector<string> ip;
istringstream iss(str);
for(string str; iss >> str; )
ip.push_back(str);
// Create the root of the tree
Node* root = newNode(stoi(ip[0]));
// Push the root to the queue
queue<Node*> queue;
queue.push(root);
// Starting from the second element
int i = 1;
while(!queue.empty() && i < ip.size()) {
// Get and remove the front of the queue
Node* currNode = queue.front();
queue.pop();
// Get the current node's value from the string
string currVal = ip[i];
// If the left child is not null
if(currVal != "N") {
// Create the left child for the current node
currNode->left = newNode(stoi(currVal));
// Push it to the queue
queue.push(currNode->left);
}
// For the right child
i++;
if(i >= ip.size())
break;
currVal = ip[i];
// If the right child is not null
if(currVal != "N") {
// Create the right child for the current node
currNode->right = newNode(stoi(currVal));
// Push it to the queue
queue.push(currNode->right);
}
i++;
}
return root;
}
struct Node
{
int data;
struct Node* left;
struct Node* right;
Node(int x){
data = x;
left = right = NULL;
}
};
class Solution
{
public:
//Function to convert binary tree to doubly linked list and return it.
void solve(Node* root, Node* &head, Node* &prev) {
if(root == NULL) {
return;
}
solve(root->left, head, prev);
if(prev == NULL) head = root;
else {
prev->right = root;
root->left = prev;
}
prev = root;
solve(root, head, prev);
return head;
}
};
/* Function to print nodes in a given doubly linked list */
{
Node *prev = NULL;
while (node!=NULL)
{
cout << node->data << " ";
node = node->right;
while (prev!=NULL)
{
cout << prev->data << " ";
prev = prev->left;
}
}
void inorder(Node root)
{
if (root != NULL)
{
inorder(root->left);
inorder(root->right);
}
}
main()
{
int t;
cin >> t;
getchar();
while (t--)
{
string inp;
getline(cin, inp);
Node *root = buildTree(inp);
}

Step by step
Solved in 3 steps with 1 images









