有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java在BFS中创建接受用户输入的树

我很困惑如何在穿越BFS时保持树的顶部。我接受这样的输入:

5 // total number of nodes in tree (root node will always be 1)
  // this number also tells the number of lines that'll be coming up
2 3 // left and right child of root, tree be like : 1
                                                   / \
                                                  2   3
4 5 // left and right child of 2 , tree             1
                                                   / \
                                                  2   3
                                                 / \
                                                4   5
-1 -1 // left and right child of 3 , that's null
-1 -1 // left and right child of 4
-1 -1 // left and right child of 5

这继续以上述方式进行,用户在BFS中输入左和右子级。但我无法理解我是如何做到这一点的

我的看法是:

LinkedList<Node> list = new LinkedList<Node>
list.add(root); //initially push root
while(list.peek()){  //while there is node left in linked list
    curr = list.poll();
    curr.left = new Node(x) // x = whatever is the user input is (using nextInt)
                            // and if it's -1, i'll make left child null
    curr.right = new Node(x) // same goes for this one
    ll.add(curr);

}

最后,我需要根节点的引用,我不知道如何获得它?还有,有没有更好的方法来完成这个任务


共 (1) 个答案

  1. # 1 楼答案

    我希望下面的代码可以帮助您

    “readTree”函数用于读取树

    public static Node readTree(Scanner in) {
        Queue<Node> queue = new LinkedList<Node>();
        Node root = new Node(1);
        queue.add(root);
        while (!queue.isEmpty()) {
            Node node = queue.poll();
            int left = in.nextInt();
            int right = in.nextInt();
            if (-1 != left) {
                node.left = new Node(left);
                queue.add(node.left);
            }
            if (-1 != right) {
                node.right = new Node(right);
                queue.add(node.right);
            }
        }
        return root;
    }
    
    public static void main(String[] args) {
        Scanner in = new Scanner(System.in);
        in.nextInt(); // number of nodes is not used.
        Node result = readTree(in);
    }