二叉樹的打印分爲兩種,橫向打印和縱向打印。
1 橫向打印算法
void show(TreeNode *parent,TreeNode* root,string &prefix){
prefix += "|";
if (root){
cout << prefix<<"--" << root->val << endl;
if (root==parent||root == parent->right){
prefix.pop_back(); prefix += " ";
}
show(root,root->left, prefix+" ");
show(root,root->right, prefix+" ");
}else{
if (parent->left || parent->right) //有一個孩子節點不空就打印,以區分左右孩子
cout << prefix << "--" << "{}"<< endl;
}
}
2 縱向打印算法
主要使用二叉樹的層序遍歷,過程中按照中序序列確定每個節點列的位置
void Tree::disp(){
queue<TreeNode *> q;
q.push(this->root);
string InOrd;
this->InOrder(this->root,InOrd);//獲得中序遍歷序列
while (!q.empty()){
vector<TreeNode*> cache;
//把處在同一行的節點拉出來
while (!q.empty()){ cache.push_back(q.front()); q.pop(); }
string line = " ";
for (auto p:cache)
if (p){
//找當前節點中序遍歷位置
line[InOrd.find(p->val)] = p->val;
//孩子節點入隊
if (p->left) q.push(p->left);
if (p->right) q.push(p->right);
}
cout << line << endl;
}
}
//==================中序遍歷===========================
void Tree::InOrder(TreeNode* root,string &In){
if (root){
InOrder(root->left, In);
In += root->val;
InOrder(root->right, In);
}
}
效果如圖: