假设二叉树的数据元素为字符,采用二叉链式存储结构。二叉树ADT实现的大部分代码已经给出,其中二叉树采用完全前序序列创建。请补充一个二叉树的输出函数,要求按目录缩进的形式输出一棵二叉树,同时要输出目录的层次。层次占2位、元素占1位,间隔4个位置(即共占7个位置)。 注意:答案区只写指定补充的函数代码,其他给定的代码不允许重写、修改和提交!
例如:有如右图的二叉树
输入:ABD@@E@@C@F@@
输出:
1A
2B
3D
3E
2C
3F
给出的代码如下:
#include <iostream>
#include <stdlib.h>
#include<stdio.h>
using namespace std;
//数据元素类型
typedef char ElemType;
//二叉树结点定义
typedef struct TreeNode
{ ElemType data;
struct TreeNode *lson, *rson;
} TreeNode;
//二叉树类
class BinaryTree
{ private:
TreeNode *root;
public:
BinaryTree() { root = NULL; };
~BinaryTree() { MakeEmpty(root); }
void MakeEmpty(TreeNode *t);
void create( ) { root = cp_create(root); }; //完全前序建立二叉树,空指针用@表示
TreeNode *cp_create(TreeNode *t);
void output( ) { Index_print(root,1); };
//*********** 下面是需要自己完成的函数 ******************
void Index_print(TreeNode *t,int l); //缩进目录形式输出二叉树
};
//二叉树置空
void BinaryTree::MakeEmpty(TreeNode *t)
{ if (t != NULL)
{ MakeEmpty(t->lson);
MakeEmpty(t->rson);
delete t;
}
}
//完全前序序列创建二叉树,空指针用@表示
TreeNode *BinaryTree::cp_create(TreeNode *t)
{ ElemType v;
cin >> v;
if (v != '@')
{ t = new TreeNode;
t->data = v;
t->lson = cp_create(t->lson);
t->rson = cp_create(t->rson);
}
else t = NULL;
return t;
}
//*****下面是要补充的函数Index_print *************
//*************************************************
//主函数
int main()
{ BinaryTree t;
t.create(); //创建二叉树
t.output(); //按规定格式输出二叉树
cout<< endl;
return 0;
}
///递归求解
void BinaryTree::Index_print(TreeNode* t, int l)
{
if (t==NULL) return ;
for(int i=0;i<l-1;i++)
{
cout<<" ";
}
printf("%2d",l);
cout<<t->data<<endl;
Index_print(t->lson,l+1);
Index_print(t->rson,l+1);
}
输入 | 期望输出 | 实际输出 | ||
---|---|---|---|---|
AB@@C@@ | 1A 2B 2C | 1A 2B 2C |