import java.util.*;
public class Main { static class TreeNode { int val; TreeNode left; TreeNode right;
TreeNode() { }
TreeNode(int val) { this.val = val; }
TreeNode(int val, TreeNode left, TreeNode right) { this.val = val; this.left = left; this.right = right; } }
public static void main(String[] args) { Scanner sc = new Scanner(System.in);
int numberOfNode = sc.nextInt(); HashMap<Integer, TreeNode> nodeMap = new HashMap<>(); int rootVal = sc.nextInt(); TreeNode root = new TreeNode(rootVal); int firstChildVal = sc.nextInt(); TreeNode firstChild = new TreeNode(firstChildVal); root.left = firstChild;
nodeMap.put(firstChildVal, firstChild); nodeMap.put(rootVal, root);
for (int i = 0; i < numberOfNode - 2; i++) { int parentVal = sc.nextInt(); int childVal = sc.nextInt(); TreeNode child = new TreeNode(childVal); TreeNode parent = nodeMap.get(parentVal);
if (parent != null) { if (parent.left == null) { parent.left = child; } else if (parent.right == null) { parent.right = child; } } else { parent = new TreeNode(parentVal); parent.left = child; }
nodeMap.put(parentVal, parent); nodeMap.put(childVal, child); }
sc.close(); } }
|