美文网首页
2.直观打印二叉树

2.直观打印二叉树

作者: 山行牧野 | 来源:发表于2019-07-22 15:22 被阅读0次

    首先,Node.java文件同上
    然后打印:

    
    public class printTree {
    
        public String getSpace(int num)
        {
            String space = " ";
            StringBuffer buf = new StringBuffer("");
            for(int i=0;i<num;i++)
            {
                buf.append(space);
            }
            return buf.toString();
        }
        
        public void printBinaryTree(Node head)
        {
            System.out.println("BinaryTree:");
            printInOrder(head,0,"H",17);
            System.out.println();
        }
        
        public void printInOrder(Node head,int height,String to,int len)
        {
            if(head == null)
            {
                return;
            }
            printInOrder(head.left, height+1, "v", len);
            
            String val = to+head.value+to;
            int lenV = val.length();
            int lenL = (len - lenV)/2;
            int lenR = len - lenL - lenV;
            val = getSpace(lenL)+val+getSpace(lenR);
            System.out.println(getSpace(height*len)+val);
            
            printInOrder(head.right,height+1,"^",len);
        }
    }
    
    

    相关文章

      网友评论

          本文标题:2.直观打印二叉树

          本文链接:https://www.haomeiwen.com/subject/dvrwlctx.html