二叉树模拟,然后按层遍历,先根据输入建树,注意如果有PATH相同但值不同的点要马上判出来并break,我这里忘了跳出循环WA了几次。。悲剧,建好树后用一个队列去按层遍历,类似BFS,然后把结果存起来比较原先的输入看节点数量是否一致,不一致就不是complete,否则输出结果
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main
{
static class Node
{
int value;
Node left;
Node right;
public Node()
{
this.value = -1;
this.left = null;
this.right = null;
}
}
public static void main(String[] args)
{
Scanner sc = new Scanner(System.in);
List<String> src = new ArrayList<String>();
while (sc.hasNextLine())
{
String line = sc.nextLine();
String ss[] = line.split("\\s+");
for (String s : ss)
if (!s.trim().isEmpty())
{
if (s.trim().equals("()"))
{
resolve(src);
src.clear();
}
else
src.add(s.trim());
}
}
sc.close();
}
static void resolve(List<String> src)
{
Map<String, Integer> map = new HashMap<String, Integer>();
boolean flag = true;
for (String s : src)
{
String[] arr = s.split(",");
int value = Integer.valueOf(arr[0].substring(1));
String path = arr[1].substring(0, arr[1].length() - 1);
if (map.containsKey(path) && !(map.get(path) == value))
{
flag = false;
System.out.println("not complete");
break;
}
else
map.put(path, value);
}
if (!flag)
return;
Node tree = getTree(map);
List<Integer> order = getOrder(tree);
if (order.size() != map.size())
System.out.println("not complete");
else
{
System.out.print(order.get(0));
for (int i = 1; i < order.size(); i++)
System.out.print(" " + order.get(i));
System.out.println();
}
}
static Node getTree(Map<String, Integer> map)
{
Node root = new Node();
for (String path : map.keySet())
{
Node curr = root;
for (char c : path.toCharArray())
{
if (c == 'L')
{
if (curr.left == null)
curr.left = new Node();
curr = curr.left;
}
else
{
if (curr.right == null)
curr.right = new Node();
curr = curr.right;
}
}
curr.value = map.get(path);
}
return root;
}
static List<Integer> getOrder(Node root)
{
LinkedList<Node> queue = new LinkedList<Node>();
List<Integer> result = new ArrayList<Integer>();
if (root.value != -1)
queue.addLast(root);
while (!queue.isEmpty())
{
Node curr = queue.removeFirst();
result.add(curr.value);
if (curr.left != null && curr.left.value != -1)
queue.addLast(curr.left);
if (curr.right != null && curr.right.value != -1)
queue.addLast(curr.right);
}
return result;
}
}