I have the following code for a Binary Search Tree:
#include <iostream>
#include <iomanip>
using namespace std;
struct Node {
int data;
Node* left;
Node* right;
Node(int val) {
data = val;
left = nullptr;
right = nullptr;
}
};
void insert(Node*& root, int val) {
if (root == nullptr) {
root = new Node(val);
return;
}
if (val < root->data) {
insert(root->left, val);
}
else {
insert(root->right, val);
}
}
void printTree(Node* root, int indent=0) {
if (root) {
printTree(root->right, indent+0);
if (indent) {
std::cout << std::setw(indent) << ' ';
}
if (root->right) {
std::cout << "/ \n";
}
std::cout << root->data << '\n';
if (root->left) {
std::cout << std::setw(indent) << ' ' << " \\\n";
}
printTree(root->left, indent+2);
}
}
int main() {
Node* root = nullptr;
insert(root, 9);
insert(root, 8);
insert(root, 7);
insert(root, 6);
insert(root, 5);
insert(root, 4);
insert(root, 3);
insert(root, 5);
printTree(root, 0);
return 0;
}
This is the output I'm getting:
9
\
8
\
7
\
6
\
5
/
5
\
4
\
3
Looks almost good. Just need that left most 5 to align under its parent root 5 directly. Messed around with the indentation a bit but unable to get it to work without messing up the other nodes.
What should I do to finally get the alignment right?
Expected:
9
\
8
\
7
\
6
\
5
/ \
5 4
\
3
Tried a different way:
void printTree(Node* root, int level) {
if (root == nullptr) {
return;
}
printTree(root->right, level + 1);
for (int i = 0; i < level; i++) {
std::cout << " ";
}
if (root->left != nullptr && root->right != nullptr) {
std::cout << root->data << "/ \\" << std::endl;
}
else if (root->right != nullptr) {
std::cout << root->data << " /" << std::endl;
}
else if (root->left != nullptr) {
std::cout << root->data << "\\ " << std::endl;
}
else {
std::cout << root->data << std::endl;
}
printTree(root->left, level + 1);
}
It's right, however, the display isnt as great as the method above with indentation/setw() combo (I want the slashes to represent branches on a new line not next to the node itself)
9\
8\
7\
6\
5
5/ \
4\
3