C#控制台打印二叉树

1. 先序遍历树节点,分层存储

1)计算获取NULL节点的占位符长度和所有节点字符串中的最长长度maxLength,作为box的长度

2. 从叶子节点层向上迭代计算每一层的起始点位置StartPos和节点间宽度NodeGap

1)当前层StartPos = 上一层StartPos + ( 2 * maxLenth + 上一层NodeGap ) / 2 - maxLength / 2

= 上一层StartPos + (maxLength + NodeGap) / 2

2)当前层NodeGap = ( 2 * maxLength + 2 * 上一层NodeGap) - maxLength

= 2 * NodeGap + maxLength

3. 打印字符串输出控制台:起始空格 box gap box gap .....

1)绘制节点时,需要把字符串绘制在box的中间

2)基于颜色变色处理

3)最后一位不绘制

4)绘制一层节点,就绘制连接线,这里以斜杠和反斜杠作为示例,为了保证左右孩子间距的一半等于父节点到子节点的垂线距离(如下图a和b所示,a=b),分别计算得到连接线的层数和每一层连接线的节点数

5)绘制连接线时,需要不断更新当前层的起始坐标StartPos,斜杠后的空格和反斜杠后的空格数量不同,而且连接线中的每一层斜杠间的间距不同

完整代码如下:

  public void PrintTree(int startPos = 10, int nodeGap = 3, int boxLenth = -1, string placeholder = "n")
        {
            // 先序遍历获取所有树节点  并分层存储
            var queue = new Queue<Tuple<RBNode<K, V>, int>>();
            queue.Enqueue(new Tuple<RBNode<K, V>, int>(this.root, 1));
            var dic = new Dictionary<int, List<RBNode<K,V>>>();    // 存储层号和对应节点
            int maxLength = Math.Max(placeholder.Length, boxLenth);

            while (queue.Count > 0)
            {
                var item = queue.Dequeue();
                var t = item.Item1;
                var l = item.Item2;

                if (dic.ContainsKey(l) == false)
                {
                    // 上一层全部为空
                    if (dic.ContainsKey(l - 1) && dic[l - 1].Any(p => p != null) == false) break;
                    dic[l] = new List<RBNode<K, V>>();
                }
                    
                dic[l].Add(t);

                if (t != null)
                {
                    maxLength = Math.Max(t.key.ToString().Length, maxLength);
                }
                queue.Enqueue(new Tuple<RBNode<K, V>, int>(t?.left, l + 1));
                queue.Enqueue(new Tuple<RBNode<K, V>, int>(t?.right, l + 1));
            }

            // 计算每一层节点起始字符宽度和节点间的宽度
            int height = dic.Last().Key;
            Tuple<int, int>[] locs = new Tuple<int, int>[height];   // 存储起始坐标和节点间距
            locs[locs.Length - 1] = new Tuple<int, int>(startPos, nodeGap);
            for (int i = locs.Length - 2; i >= 0; i--)
            {
                var cur = locs[i + 1];
                int nextStartPos = cur.Item1 + (maxLength + cur.Item2) / 2;
                int nextNodeGap = 2 *  cur.Item2 + maxLength;
                locs[i] = new Tuple<int, int>(nextStartPos, nextNodeGap);
            }


            // PadLeft 填充字符串  绘制二叉树
            int ind = 1;
            foreach (var item in dic.Zip(locs))
            {
                int layer = item.First.Key;
                var nodes = item.First.Value;
                int sp = item.Second.Item1;
                int ng = item.Second.Item2;
                Console.WriteLine();
                Console.Write("".PadLeft(sp, ' '));

                // 绘制节点
                int nc = 1;
                foreach (var n in nodes)
                {
                    string str = string.Empty;
                    bool isLeaf = false;
                    if (n == null)
                    {
                        var pa = dic[ind - 1][(nc - 1) / 2];
                        int a = 0;
                        if (pa?.key.ToString() == "35")
                            a = 11;
                        isLeaf = pa != null && (pa.left == n || pa.right == n);
                        if (isLeaf) str = placeholder;
                        else str = "";
                    }
                    else
                    {
                        isLeaf = true;
                        str = n.key.ToString();
                    }

                    var l = str.Length;
                    var pos = (maxLength - l) / 2;
                    string merge = "".PadLeft(pos, ' ') + str + "".PadRight(maxLength - pos - str.Length, ' ');

            
                    ChangeColor(n);
                    if (isLeaf == false) ClearColor();
                    Console.Write(merge);
                    ClearColor();

                    if (nc < nodes.Count)   // 不是最后一位
                        Console.Write("".PadLeft(ng, ' '));
                    
                   
                    nc++;
                }

                if (ind == height) break;

                // 绘制连接线
                sp = sp + maxLength / 2;
                int layerCount = (locs[ind].Item2 + maxLength) / 2;  // 保证左右孩子间距的一半等于父节点到子节点的垂线距离
                int charLenth = 1;
                for (int i = 0; i < layerCount; i++)
                {
                    sp--;
                    Console.WriteLine();
                    Console.Write("".PadLeft(sp, ' '));
                    int nodeCount = (int)Math.Pow(2, ind);
                    int charGap = i * 2;
                    for (int j = 0; j < nodeCount; j++)
                    {
                        // 空节点不画下方的连接线
                        bool isEmptyNode = nodes[j / 2] == null;  

                        if (j % 2 == 0)
                        {
                            string c = isEmptyNode ? " " : "/";
                            Console.Write(c.PadRight(charGap + 1, ' '));
                        }
                        else
                        {
                            string c = isEmptyNode ? " " : "\\";
                            Console.Write(c);
                            // 不是最后一位
                            if (j < nodeCount - 1)
                                Console.Write("".PadLeft(ng + maxLength - charGap - 2 * charLenth, ' '));
                        }

                    }
                }

                ind++;

            }

        }
        private void ChangeColor(RBNode<K, V> n)
        {
            if (n == null || n.color == BLACK)
            {
                Console.BackgroundColor = ConsoleColor.DarkGray;
                Console.ForegroundColor = ConsoleColor.White;
            }
            else
            {
                Console.BackgroundColor = ConsoleColor.Red;
                Console.ForegroundColor = ConsoleColor.White;
            }
        }
        private void ClearColor()
        {
            Console.BackgroundColor = ConsoleColor.Black;
            Console.ForegroundColor = ConsoleColor.White;
        }

调用效果如下:

 

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
/* 这是一个在字符环境中,用ASCII码打印二叉树形状的算法。 在Linux控制台下写的例题,在DOS中稍有点乱。 采用层次遍法。 算法拙劣,仅供初学者做练习,(本人也是初学者,自学数据结构,刚好学到这二叉树这一章, 半路出家,基础差有点吃力头大,搞几个二叉的例题,却不知道其构造形状, 想调用图形API做个美观点的,却有点偏离本章的学习目的,只好用字符打印, linux环境中打印的还可以,DOS中有点不稳定,如果您有更好的算法一定不吝赐教。 我的QQ:137241638 mail:[email protected] */ #include <stdio.h> #include <stdlib.h> #define MaxSize 100 //Pstart是二叉树根结点在一行中的位置,一行最能打印124个字符,取其1/2。 //如果你的屏不够宽的话,可以输出文本文件里, aa.exe>>aa.txt #define Pstart 40 typedef struct bstnode { int key, data, bf; struct bstnode *lchild, *rchild; }BSTNode; typedef struct pnode //为打印二叉树建了一个结构。 { int key; //关键字数据1 int data; //关键字数据2 struct pnode *lchild, //左孩子 *rchlid, //右孩子 *parent; //父节点 int lrflag, //标记本节点是左孩子(等于0时),还是右孩子(等于1时) space, //存储本节点打印位置 level; //存储本节点所在层次。 }PBSTNode; /*建立二叉树。 用括号表示法表示二叉树字符串,创建二叉树。 */ BSTNode* CreateBSTNode(char *s) { char ch; BSTNode *p=NULL, *b=NULL, *ps[MaxSize]; int top=-1, tag=-1; ch=*s; while(ch) { switch(ch) { case '(':ps[++top]=p;tag=1;break; case ',':tag=2;break; case ')':top--;break; default: p=(BSTNode*)malloc(sizeof(BSTNode)); p->data=ch; p->lchild=p->rchild=NULL; if(b==NULL) b=p; else { switch(tag) { case 1:ps[top]->lchild=p;break; case 2:ps[top]->rchild=p;break; } } } ch=*(++s); } return b; } //用适号表示法打印二叉树。 void DispBSTNode(BSTNode *b) { if(b!=NULL) { printf("%d",b->key); if(b->lchild!=NULL||b->rchild!=NULL) { printf("("); DispBSTNode(b->lchild); if(b->rchild!=NULL)printf(","); DispBSTNode(b->rchild); printf(")"); } } } int BSTNodeHeight(BSTNode *b) { int lchildh,rchildh; if(b==NULL)return 0; else { lchildh=BSTNodeHeight(b->lchild); rchildh=BSTNodeHeight(b->rchild); return (lchildh>rchildh)?(lchildh+1):(rchildh+1); } } /*建立一个二叉树打印结点的信息, 只被int CreatePBSTNode(BSTNode *b,PBSTNode *pqu[])调用*/ void SetPBSTNodeInfo(BSTNode *b,PBSTNode *parent,PBSTNode *pb,int level,int lrflag) { int f=3; pb->data=b->data; pb->key =b->key; pb->parent=parent; pb->level=level; pb->lrflag=lrflag; pb->space=-1; } /*用层次遍历法,BSTNode结构存储的二叉树转换为,PBSTNode结构的二叉树*/ int CreatePBSTNode(BSTNode *b,PBSTNode *pqu[]) { BSTNode *p; BSTNode *qu[MaxSize]; int front=-1, rear=-1; rear++; qu[rear]=b; pqu[rear]=(PBSTNode*)malloc(sizeof(PBSTNode)); SetPBSTNodeInfo(b,NULL,pqu[rear],1,-1); while(rear!=front) { front++; p=qu[front]; if(p->lchild!=NULL) { rear++; qu[rear]=p->lchild; pqu[rear]=(PBSTNode*)malloc(sizeof(PBSTNode)); SetPBSTNodeInfo(p->lchild,pqu[front],pqu[rear],pqu[front]->level+1,0); } if(p->rchild!=NULL) { rear++; qu[rear]=p->rchild; pqu[rear]=(PBSTNode*)malloc(sizeof(PBSTNode)); SetPBSTNodeInfo(p->rchild,pqu[front],pqu[rear],pqu[front]->level+1,1); } } return rear; } //打印一层结点,及该层结点与父结点的连线路径。 void PBSTNodePrint_char(PBSTNode *pb[],int n,int h) { int l=-1, r=0, i,j,k, end; char c; PBSTNode *p; if(n<=0||h<=0) { return; } else if(pb[0]->level==1) { for(i=0;i<pb[0]->space;i++) printf(" "); printf("%c",pb[0]->data); printf("\n"); return; } h=h-pb[0]->level+2; for(k=0;k<h;k++) { j=0; l--; r++; for(i=0;i<n;i++)//打印线条 { p=pb[i]; end=(p->lrflag==0)?l:r; end+=p->parent->space; for(;j<end;j++) printf(" "); c=(p->lrflag==0)?'/':'\\'; printf("%c",c); } printf("\n"); } for(i=0;i<n;i++)//计算本层结点打印位置 { p=pb[i]; if(p->lrflag==0) p->space=p->parent->space+l; else p->space=p->parent->space+r; } for(i=0,j=0;i<n;i++)//打印关键字数据 { p=pb[i]; for(;j<p->space;j++) printf(" "); printf("%c",p->data); } printf("\n"); } //循环打印所有层的数据 void DispBTree(BSTNode *b) { int n,i,j,high, level; PBSTNode *p; PBSTNode *pqu[MaxSize]; PBSTNode *levelpqu[MaxSize]; n=CreatePBSTNode(b,pqu); high=BSTNodeHeight(b); j=0; level=1; pqu[0]->space=Pstart; for(i=0;i<=n;i++) { p=pqu[i]; if(p->level==level) { levelpqu[j]=p; j++; } else { PBSTNodePrint_char(levelpqu,j,high); level=p->level; j=0; levelpqu[j]=p; j++; } } PBSTNodePrint_char(levelpqu,j,high); } void main() { int iDepth=0, iWidth=0, iCount=0; char *str1="A(B(D,E(H,X(J,K(L,M(T,Y))))),C(F,G(X,I)))"; char *str2="A(B(D(,G)),C(E,F))"; BSTNode *b=CreateBSTNode(str1); DispBSTNode(b);printf("\n"); iDepth=BSTNodeHeight(b); printf("Depth:%d\n",iDepth); DispBTree(b); }

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值