数据结构与算法(按目录缩进的形式输出二叉树)

假设二叉树的数据元素为字符,采用二叉链式存储结构。二叉树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)
    {
        for(int i=1;i<=l-1;i++)printf("       ");//7个空格
        printf("%2d",l);
        printf("%c\n",t->data);
        Index_print(t->lson,l+1);
        Index_print(t->rson,l+1);
    }
}
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值