在Java的控制台外壳中漂亮地打印一棵树

时间:2018-09-03 14:32:30

标签: java tree

如果您正在研究树,最有效的实现方法之一就是将其打印出来的一种清晰方法,在以下我用Java打印树的解决方案中:

public void printTree(NodeRB tree, String indent, boolean print_leaf) {
    if(tree == NILL) {
        System.out.print((print_leaf?indent+"   |-+*\n":""));
    } else { 
        indent += "   ";
        if(tree.p == NILL || tree.p == null) {
            printTree(tree.right, indent + " ", print_leaf);
            System.out.print(indent + "+" + tree.value + "\n");
            printTree(tree.left, indent + " ", print_leaf);
        }else if(tree.p.right==tree) {
            printTree(tree.right, indent + " ", print_leaf);
            System.out.print(indent + "|+" + tree.value + "\n");
            printTree(tree.left, indent + "|", print_leaf);
        }
        else {  
            printTree(tree.right, indent + "|", print_leaf);
            System.out.print(indent + "|+" + tree.value + "\n");
            printTree(tree.left, indent + " ", print_leaf);

        }
    }

}

有人有改进建议吗?

0 个答案:

没有答案