在Java中以树状结构打印值吗?

时间:2018-11-06 16:46:25

标签: java tree treenode

我正在尝试编写此代码,以在下面的树结构中打印给定的用户输入

      x
  x       x
x            x

,但不会以这种方式输出。 我得到的输出为

x
x
x

这是我编写的获取并打印的功能:

private void inOrder(Node n)
{
    if(n == null) // recursion ends when node is null
    return;
{
    inOrder(n.left);
    System.out.println(n.data);
    inOrder(n.right);
}
}

public void printInorder()
{
    inOrder(root);
}

3 个答案:

答案 0 :(得分:0)

在打印所需方式时遇到问题。 依次打印左,当前和右。这些在树中处于不同级别。一旦您打印了下一层,您就无法再打印上面的当前层,因为它已经被打印了。

也不要忘记println将打印该字符串并在其后添加新行。

要进行精美的设计,您可能需要进行一些精美的工程设计以使其完美对齐,如下所示:

您需要一个队列来访问节点。

printNode(Node root, queueWithNodesAndStartAndEnd, start, end)
   print me at the middle of start and end
   put my left child in the queue with start = myStart and end = middle of my start and my end
   put my right child in the queue with start = middle of my start and my end and end  = my end
   pop (get and remove) first element from queue
   if not empty print popped node with start and end provided

我知道这是伪代码,但是您应该能够实现它。

答案 1 :(得分:0)

一个有趣的运动!您的方法遇到了麻烦,因为对println()的任何调用都排除了在一行上打印更多节点的麻烦。使用level order traversal/BFS可使您仅在完成给定树级上的所有节点的打印后才能调用println()移至下一行。

更大的困难在于跟踪每个节点在水平中的水平位置。正确执行此操作需要考虑节点数据的深度,长度和空子级。如果允许,请考虑打印树,其深度从左至右增加,类似于unix命令tree,而不是自上而下。

这里是一个简单的概念验证,以说明自上而下的打印内容可能是什么(关于这个主题,this excellent post中的公式之间的空格/之间)。我使用的策略是使用队列运行BFS,在每个级别的列表中存储节点(和空值)。一旦到达级别的末尾,将根据级别上的节点数2 n-1 确定前/分隔空间,然后打印。

import java.util.*;


class Main {
    public static void main(String[] args) {
        printLevelOrder(
            new Node(
                1, 
                new Node(
                    2, 
                    new Node(
                        4, 
                        new Node(7, null, null), 
                        null
                    ),
                    null
                ),
                new Node(
                    3, 
                    new Node(
                        5, 
                        new Node(8, null, null),
                        null
                    ),
                    new Node(
                        6, 
                        null,
                        new Node(9, null, null)                        
                    )
                )
            )
        );
    }

    static void printLevelOrder(Node root) {
        LinkedList<Item> queue = new LinkedList<>();
        ArrayList<Node> level = new ArrayList<>();
        int depth = height(root, 0);
        queue.add(new Item(root, depth));

        for (;;) {
            Item curr = queue.poll();

            if (curr.depth <= 0) {
                for (Node n : level) {
                    System.out.print((n == null ? " " : n.val) + " "); 
                }

                System.out.println();
                break;
            }
            else if (curr.depth < depth) {
                depth = curr.depth;

                for (int i = (int)Math.pow(2, depth) - 1; i > 0; i--) { 
                    System.out.print(" "); 
                }

                for (Node n : level) {
                    System.out.print((n == null ? " " : n.val));

                    for (int i = (int)Math.pow(2, depth + 1); i > 1; i--) {
                        System.out.print(" ");
                    }
                }

                level.clear();
                System.out.println();
            }

            if (curr.node != null) {
                level.add(curr.node);
                queue.add(new Item(curr.node.left, depth - 1));
                queue.add(new Item(curr.node.right, depth - 1));
            }
            else {
                level.add(null);
                queue.add(new Item(null, depth - 1));
                queue.add(new Item(null, depth - 1));
            }
        }
    }

    static int height(Node root, int height) {
        if (root != null) {
            return 1 + Math.max(
                height(root.left, height), 
                height(root.right, height)
            );
        }

        return height;
    }
}

class Node {
    Node left;
    Node right;
    int val;

    public Node(int val, Node left, Node right) {
        this.left = left;
        this.right = right;
        this.val = val;
    }
}

class Item {
    Node node;
    int depth;
    int width;

    public Item(Node node, int depth) {
        this.node = node;
        this.depth = depth;
    }
}

输出:

       1               
   2       3       
 4       5   6   
7       8     9 

Try it!

答案 2 :(得分:0)

这是我见过的最好的解决方案:https://stackoverflow.com/a/42449385/9319615

这是我利用它的代码段。此类将按原样运行。

class Node {
    final int value;
    Node left;
    Node right;

    Node(int value) {
        this.value = value;
        right = null;
        left = null;
    }

    public void print() {
        print("", this, false);
    }

    private void print(String prefix, Node n, boolean isLeft) {
        if (n != null) {
            System.out.println(prefix + (isLeft ? "|-- " : "\\-- ") + n.value);
            print(prefix + (isLeft ? "|   " : "    "), n.left, true);
            print(prefix + (isLeft ? "|   " : "    "), n.right, false);
        }
    }


}

class BinaryTree {
    Node root;

    private Node addRecursive(Node current, int value) {
        if (current == null) {
            return new Node(value);
        }

        if (value < current.value) {
            current.left = addRecursive(current.left, value);
        } else if (value > current.value) {
            current.right = addRecursive(current.right, value);
        } else {
            // value already exists
            return current;
        }

        return current;
    }

    public void add(int value) {
        root = addRecursive(root, value);
    }

    public void traverseInOrder(Node node) {
        if (node != null) {
            traverseInOrder(node.left);
            System.out.print(" " + node.value);
            traverseInOrder(node.right);
        }
    }


}

public class Main {

    public static void main(String[] args) {

        BinaryTree bt = new BinaryTree();
        bt.add(6);
        bt.add(4);
        bt.add(8);
        bt.add(3);
        bt.add(5);
        bt.add(7);
        bt.add(9);

        System.out.println("Print in order->");
        bt.traverseInOrder(bt.root);

        System.out.println("\n\nPrint Tree Structure");
        bt.root.print();
    }

}

Output example