I am a \"bit\" lost trying to print a binary tree like below in c++:
8
/ \\
/ \\
/ \\
5 10
/
Even tough it is not exactly what you asked for, printing trees horizontally is way simpler. And especially in case of large trees, I think this is the better representation form.
└──8
├──5
│ ├──2
│ └──6
└──10
├──9
└──11
Following C++ code roots in this java implementation.
void printBT(const std::string& prefix, const BSTNode* node, bool isLeft)
{
if( node != nullptr )
{
std::cout << prefix;
std::cout << (isLeft ? "├──" : "└──" );
// print the value of the node
std::cout << node->m_val << std::endl;
// enter the next tree level - left and right branch
printBT( prefix + (isLeft ? "│ " : " "), node->m_left, true);
printBT( prefix + (isLeft ? "│ " : " "), node->m_right, false);
}
}
void printBT(const BSTNode* node)
{
printBT("", node, false);
}
// pass the root node of your binary tree
printBT(root);