写二叉树的程序时经常会遇到希望漂亮地把二叉树给输出,本文给出了一个小程序。
以下时打印的效果:
// ag真人试玩娱乐 copyright @ l.j.shou jan.16, 2014
// a fancy binary tree printer
#ifndef binary_tree_printer_h_
#define binary_tree_printer_h_
#include
#include
#include
using std::vector;
using std::cout;
using std::endl;
using std::max;
void printbinarytree(treenode *root);
struct treenode
{
treenode *left;
treenode *right;
int val;
treenode(int x=0)
: val(x), left(null), right(null){}
};
static int maxlevel(treenode *root)
{
if(root == null) return 0;
return max(maxlevel(root->left), maxlevel(root->right)) 1;
}
// test whether all elements in vector are null
static bool isallelementsnull(const vector &nodes)
{
vector::const_iterator it = nodes.begin();
while(it != nodes.end()){
if(*it) return false;
it;
}
return true;
}
static void printwhitespaces(int num)
{
for(int i=0; i &nodes, int level, int max_level)
{
if(nodes.empty() || isallelementsnull(nodes)) return; // exit
int floor = max_level - level;
int endge_lines = 1 << (max(floor-1, 0));
int first_spaces = (1 << floor) - 1;
int between_spaces = (1 << (floor 1)) - 1;
printwhitespaces(first_spaces);
// print the 'level' level
vector new_nodes;
vector::const_iterator it = nodes.begin();
for(; it != nodes.end(); it){
if(*it != null){
cout << (*it)->val;
new_nodes.push_back((*it)->left);
new_nodes.push_back((*it)->right);
}
else{
new_nodes.push_back(null);
new_nodes.push_back(null);
cout << " ";
}
printwhitespaces(between_spaces);
}
cout << endl;
// print the following /s and \s
for(int i=1; i<= endge_lines; i){
for(int j=0; jleft != null)
cout << "/";
else
printwhitespaces(1);
printwhitespaces(i i-1);
if(nodes[j]->right != null)
cout << "\\";
else
printwhitespaces(1);
printwhitespaces(endge_lines endge_lines - i);
}
cout << endl;
}
printnode(new_nodes, level 1, max_level);
}
// wrapper function
void printbinarytree(treenode *root)
{
int max_level = maxlevel(root);
vector nodes;
nodes.push_back(root);
printnode(nodes, 1, max_level);
}
#endif
#if 0
int main(void)
{
treenode *root(null);
root = new treenode(1);
root->left = new treenode(2);
root->right = new treenode(3);
root->left->left = new treenode(4);
root->right->right = new treenode(7);
root->left->left->left = new treenode(8);
root->left->left->right = new treenode(9);
printbinarytree(root);
root = destroy(root);
return 0;
}
#endif