| 17 | |
| 18 | |
| 19 | Node *buildTree (string str) { |
| 20 | // Corner Case |
| 21 | if (str.length() == 0 || str[0] == 'N') |
| 22 | return NULL; |
| 23 | |
| 24 | // Creating vector of strings from input |
| 25 | // string after spliting by space |
| 26 | vector<string> ip; |
| 27 | |
| 28 | istringstream iss(str); |
| 29 | for (string str; iss >> str;) |
| 30 | ip.push_back(str); |
| 31 | |
| 32 | // Create the root of the tree |
| 33 | Node *root = new Node (stoi (ip[0])); |
| 34 | |
| 35 | // Push the root to the queue |
| 36 | queue<Node *> queue; |
| 37 | queue.push(root); |
| 38 | |
| 39 | // Starting from the second element |
| 40 | int i = 1; |
| 41 | while (!queue.empty() && i < ip.size()) { |
| 42 | |
| 43 | // Get and remove the front of the queue |
| 44 | Node *currNode = queue.front(); |
| 45 | queue.pop(); |
| 46 | |
| 47 | // Get the current Node's value from the string |
| 48 | string currVal = ip[i]; |
| 49 | |
| 50 | // If the left child is not null |
| 51 | if (currVal != "N") { |
| 52 | |
| 53 | // Create the left child for the current Node |
| 54 | currNode->left = new Node (stoi(currVal)); |
| 55 | |
| 56 | // Push it to the queue |
| 57 | queue.push(currNode->left); |
| 58 | } |
| 59 | |
| 60 | // For the right child |
| 61 | i++; |
| 62 | if (i >= ip.size()) |
| 63 | break; |
| 64 | currVal = ip[i]; |
| 65 | |
| 66 | // If the right child is not null |
| 67 | if (currVal != "N") { |
| 68 | |
| 69 | // Create the right child for the current Node |
| 70 | currNode->right = new Node (stoi(currVal)); |
| 71 | |
| 72 | // Push it to the queue |
| 73 | queue.push(currNode->right); |
| 74 | } |
| 75 | i++; |
| 76 | } |