二叉树java

rfbsl7qr  于 2021-07-06  发布在  Java
关注(0)|答案(1)|浏览(396)

如何从用户创建输入?我正在做一个二叉树编程问题,但我不知道如何让输入来自用户

public class BinaryTreeApp {

public static void main(String[] args) {

BinaryTree a = new BinaryTree();

Node root = a.createNewNode(10);
root.left = a.createNewNode(12);
root.right = a.createNewNode(15);
root.left.left = a.createNewNode(25);
root.left.right = a.createNewNode(30);
root.right.left = a.createNewNode(36);
2lpgd968

2lpgd9681#

有很多方法可以做到这一点,你需要考虑一些输入格式-可以是很多事情。例如,输入可以只是“空格”分隔的值 10 12 15 25 30 26 然后解析输入并从中构建树。在解析输入后为编写了一些伪代码

root = input[0]
queue.enqueue(root)
for i in 1 to input.size step = 2:
    current = queue.dequeue()
    current.left = input[i]
    current.right = input[i + 1]
    queue.enqueue(current.left)
    queue.enqueue(current.right)

编辑:添加了一些java代码

import java.util.Scanner;  // Import the Scanner class
import java.util.LinkedList; 
import java.util.Queue; 

public class HelloWorld{
    private static class Node{
        public Node left;
        public Node right;
        public String value;
        public Node(String v){
            value = v;
        }
    }
     public static void main(String []args){
        Scanner scanner = new Scanner(System.in);
        //String userInput = scanner.nextLine();
        String userInput = "10 12 15 25 30 26 27";
        String[] values = userInput.split(" ");
        Node root = new Node(values[0]);
        Queue<Node> q = new LinkedList<>();
        q.add(root);
        for(int i = 1; i < values.length; i = i + 2){
            Node current = q.remove();
            current.left = new Node(values[i]);
            current.right = new Node(values[i + 1]);
            q.add(current.left);
            q.add(current.right);
        }

     }
}

相关问题