Repository navigation
Expand file tree
/
Copy pathInvertBinaryTree.java
More file actions
66 lines (58 loc) · 1.87 KB
/
Copy pathInvertBinaryTree.java
File metadata and controls
66 lines (58 loc) · 1.87 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Scanner;
import java.util.function.Function;
class Solution {
public static class Node<T> {
public T val;
public Node<T> left;
public Node<T> right;
public Node(T val) {
this(val, null, null);
}
public Node(T val, Node<T> left, Node<T> right) {
this.val = val;
this.left = left;
this.right = right;
}
}
public static Node<Integer> invertBinaryTree(Node<Integer> tree) {
if (tree == null)
return null;
return new Node<Integer>(tree.val, invertBinaryTree(tree.right), invertBinaryTree(tree.left));
}
// this function builds a tree from input; you don't have to modify it
// learn more about how trees are encoded in
// https://algo.monster/problems/serializing_tree
public static <T> Node<T> buildTree(Iterator<String> iter, Function<String, T> f) {
String val = iter.next();
if (val.equals("x"))
return null;
Node<T> left = buildTree(iter, f);
Node<T> right = buildTree(iter, f);
return new Node<T>(f.apply(val), left, right);
}
public static List<String> splitWords(String s) {
return s.isEmpty() ? List.of() : Arrays.asList(s.split(" "));
}
public static <T> void formatTree(Node<T> node, List<String> out) {
if (node == null) {
out.add("x");
return;
}
out.add(node.val.toString());
formatTree(node.left, out);
formatTree(node.right, out);
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
Node<Integer> tree = buildTree(splitWords(scanner.nextLine()).iterator(), Integer::parseInt);
scanner.close();
Node<Integer> res = invertBinaryTree(tree);
ArrayList<String> resArr = new ArrayList<>();
formatTree(res, resArr);
System.out.println(String.join(" ", resArr));
}
}