LinkedIn | Phone Screen | Compact Tree Builder
Difficulty: MEDIUMCategory: InterviewExperienceFrequency: 1Asked On 2017-12-07Added By Anonymous
Source: Link
1interface CompactTreeBuilder<T> {
2 /**
3 * Given a root of a tree. The tree may be of any depth and width,
4 * i.e. each node may have any number of child nodes.
5 * This method should transform a tree in such a way
6 * that each node (except probably one) would either have N or 0 children
7 * (and one node may have a number of children between 0 and N).
8 *
9 * Algorithm may transform given tree in any way with only condition:
10 * if node A was an ascendant of node B in a source tree
11 * node B may not be an ascendant of a node A in a result tree (they may become siblings though).
12 *
13 * E.g.
14 *
15 * source: compact(A, 2) compact(A, 1) compact(A, 100)
16 *
17 * A A A A
18 * | | |_B |_B
19 * |_B |_B |_C |
20 * | | | |_D |_C
21 * | | |_D |_E |
22 * | | | |_F |_D
23 * |_C | |_E |_G |
24 * | |_D | |_H |_H |_E
25 * | |_F | |
26 * | |_C |_F
27 * |_E | |
28 * |_G |_F |_G
29 * | | |
30 * |_H |_G |_H
31 *
32 *
33 * in an example for compact(A,2) above node E is an exception node:
34 * it has 1 child while any other node has either 2 or 0 children
35 */
36 Node<T> compact(Node<T> root, int N);
37 }
38
39 class Node<T> {
40
41 private final T data;
42 private final List<Node<T>> children;
43
44 public Node(T data, List<Node<T>> children) {
45 this.data = data;
46 this.children = children;
47 }
48
49 public T getData() {
50 return data;
51 }
52
53 public List<Node<T>> getChildren() {
54 return children;
55 }
56 }
57