← 返回 optiver 的题目列表Construct Binary Tree from Parent-Child Pairs and Return S-Expression
类型:online_judge
Problem: Construct a Binary Tree from Parent-Child Pairs and Return an S-Expression
You are given a string containing multiple parent-child pairs. Each pair has the format:
(P,C)
where P is the parent node and C is the child node. Each node label is a single uppercase English letter from A to Z. For example:
(A,B) (B,C) (A,D)
means A is the parent of B, B is the parent of C, and A is the parent of D.
Validate whether the input can form a valid binary tree:
The input must consist only of valid pairs.
Pairs must be separated by exactly one space.
Each node can have at most 2 distinct children.
The whole graph must have exactly one root.
The graph must not contain a cycle.
If multiple errors exist, output the highest-priority error.
Error Types and Priority
From highest to lowest priority:
E1: Invalid Input String
E2: Duplicate Pair
E3: Parent Has More than 2 Children
E4: Multiple Roots
E5: Cycle In The Tree
As soon as a higher-priority error is found, output that error code.
Output When Valid
If the input is valid, output the S-expression of the tree.
Definition:
S-expression(node) = "(" + node.val + S-expression(child1) + S-expression(child2) + ")"
If a child does not exist, omit that subtree. If a node has two children, output them in ascending lexicographical order by node label.
Example:
Input:
(A,B) (B,C) (A,D)
Output:
(A(B(C))(D))
Input Format
Read the entire input string from standard input. It may be any string.
Output Format
If an error exists, print the error code, e.g. E1.
Otherwise, print the S-expression.
Constraints
Input length is at most 10^4.
Node labels are single uppercase letters, so there are at most 26 distinct nodes.
Example
Input
(A,B) (B,C) (A,D)
Output
(A(B(C))(D))