写二叉树的程序时经常会遇到希望漂亮地把二叉树给输出,本文给出了一个小程序。
以下时打印的效果:
// copyright @ L.J.SHOU Jan.16, 2014
// a fancy binary tree printer
#ifndef BINARY_TREE_PRINTER_H_
#define BINARY_TREE_PRINTER_H_
#include <cmath>
#include <iostream>
#include <vector>
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 b