Repository navigation
Expand file tree
/
Copy pathConstructBinaryTreeFromPreorderInorderTraversal.java
More file actions
78 lines (66 loc) · 2.47 KB
/
Copy pathConstructBinaryTreeFromPreorderInorderTraversal.java
File metadata and controls
78 lines (66 loc) · 2.47 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
67
68
69
70
71
72
73
74
75
76
77
78
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Scanner;
import java.util.stream.Collectors;
import java.util.Map;
import java.util.HashMap;
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;
}
}
private static Node<Integer> buildTreeRecursive(List<Integer> preorder, Map<Integer, Integer> inorderIndexMap,
int preorderStart, int inorderStart, int size) {
if (size <= 0) {
return null;
}
int rootValue = preorder.get(preorderStart);
int inorderIndex = inorderIndexMap.get(rootValue);
int leftSize = inorderIndex - inorderStart;
Node<Integer> left = buildTreeRecursive(preorder, inorderIndexMap, preorderStart + 1, inorderStart, leftSize);
Node<Integer> right = buildTreeRecursive(preorder, inorderIndexMap, preorderStart + 1 + leftSize, inorderIndex + 1,
size - 1 - leftSize);
return new Node<Integer>(rootValue, left, right);
}
public static Node<Integer> constructBinaryTreeFromPreorderAndInorderTraversal(List<Integer> preorder,
List<Integer> inorder) {
Map<Integer, Integer> inorderIndexMap = new HashMap<>();
for (int i = 0; i < inorder.size(); i++) {
inorderIndexMap.put(inorder.get(i), i);
}
return buildTreeRecursive(preorder, inorderIndexMap, 0, 0, inorder.size());
}
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);
List<Integer> preorder = splitWords(scanner.nextLine()).stream().map(Integer::parseInt)
.collect(Collectors.toList());
List<Integer> inorder = splitWords(scanner.nextLine()).stream().map(Integer::parseInt).collect(Collectors.toList());
scanner.close();
Node<Integer> res = constructBinaryTreeFromPreorderAndInorderTraversal(preorder, inorder);
ArrayList<String> resArr = new ArrayList<>();
formatTree(res, resArr);
System.out.println(String.join(" ", resArr));
}
}