打印二叉树节点

时间:2012-04-01 16:56:19

标签: c++ data-structures recursion binary-tree

我正在编写BinaryTree项目。我完成了所有(插入,删除,创建,查找)但一个功能,即打印操作。我打算像这样打印出来:

5
46
X557
XXX6XXX9

基本上打印所有节点,但如果节点为空则打印X.我一直试图弄清楚如何做到这一点,我一直在走向死胡同。这会像inorder-traversal?谢谢

3 个答案:

答案 0 :(得分:3)

使用Level-Order遍历(广度优先搜索)在您浏览关卡时打印每个节点,并在每个级别的末尾添加换行符。

您可以找到BFS伪代码here

答案 1 :(得分:0)

您可以使用BFS但稍作修改:

在简单的BFS中,在访问节点后,将其子节点添加到队列中。如果没有孩子, 什么也没有添加。

对于您的问题,如果访问的节点没有子节点,请将特殊节点添加到队列中,其值为“x”,以便相应地在输出中打印“X”。在每个级别后打印换行符。

答案 2 :(得分:0)

正如Dream Lane所说,BFS会在这里工作。我在这里提供了自己的JAVA实现供您参考。

public static void printBST(Node root) {
    // empty tree
    if (root == null)
        return;

    Queue<Node> que = new LinkedList<Node>();
    que.add(root);
    boolean allChildNull = false;// end condition

    while (que.size() > 0 && !allChildNull) {
        allChildNull = true;
        Queue<Node> childQue = new LinkedList<Node>();

        for (Node n : que) {
            // print out noe value, X for null
            if (n == null)
                System.out.printf("%1$s", "X");
            else
                System.out.printf("%1$s", n.value);

            // add next level child nodes
            if (n == null) {
                childQue.add(null);
                childQue.add(null);
            } else {
                childQue.add(n.left);
                childQue.add(n.right);
                if (n.left != null || n.right != null)
                    allChildNull = false;
            }
        }
        System.out.printf("\n");// newline
        que = childQue;
    }
}
相关问题