HDU1622 java
时间: 2023-12-18 07:29:56 浏览: 40
根据提供的引用内容,HDU1622是一道关于二叉树的题目,要求读入一系列二叉树的节点信息,输出它们的层序遍历结果。如果输入的二叉树不完整或存在重复节点,则输出"not complete"。下面是Java的实现代码:
```java
import java.util.LinkedList;
import java.util.Queue;
import java.util.Scanner;
public class Main {
static class Node {
int val;
Node left, right;
public Node(int val) {
this.val = val;
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
while (sc.hasNext()) {
String s = sc.nextLine();
if (s.isEmpty()) {
continue;
}
String[] nodes = s.split("\\s+");
Node root = new Node(Integer.parseInt(nodes[0].substring(1)));
Queue<Node> queue = new LinkedList<>();
queue.offer(root);
boolean isComplete = true;
for (int i = 1; i < nodes.length - 1; i += 2) {
Node cur = queue.poll();
if (!nodes[i].equals("()")) {
cur.left = new Node(Integer.parseInt(nodes[i].substring(1)));
queue.offer(cur.left);
} else {
isComplete = false;
}
if (!nodes[i + 1].equals("()")) {
cur.right = new Node(Integer.parseInt(nodes[i + 1].substring(0, nodes[i + 1].length() - 1)));
queue.offer(cur.right);
} else {
isComplete = false;
}
}
if (!isComplete) {
System.out.println("not complete");
continue;
}
StringBuilder sb = new StringBuilder();
queue.offer(root);
while (!queue.isEmpty()) {
Node cur = queue.poll();
sb.append(cur.val).append(" ");
if (cur.left != null) {
queue.offer(cur.left);
}
if (cur.right != null) {
queue.offer(cur.right);
}
}
System.out.println(sb.toString().trim());
}
}
}
```