-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathBinaryTreeWalking.java
104 lines (89 loc) · 2.84 KB
/
BinaryTreeWalking.java
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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package by.andd3dfx.tree;
import lombok.Data;
import lombok.RequiredArgsConstructor;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Queue;
/**
* <pre>
* Дан класс Node:
* class Node {
* int value;
* Node left, right;
* }
*
* Реализовать алгоритм обхода бинарного дерева из нод, чтобы в итоге развернуть его в список.
* Исходно - дана корневая нода.
* </pre>
*
* @see <a href="https://youtu.be/cEd6CPAp90I">Video solution</a>
*/
public class BinaryTreeWalking {
@Data
@RequiredArgsConstructor
public static class Node<T> {
private final T value;
private final Node<T> left;
private final Node<T> right;
}
public <T> List<Node<T>> breadthWalk(Node<T> root) {
List<Node<T>> result = new ArrayList<>();
Queue<Node> children = new ArrayDeque<>();
children.add(root);
while (!children.isEmpty()) {
Node node = children.remove();
// process node
result.add(node);
if (node.left != null) {
children.add(node.left);
}
if (node.right != null) {
children.add(node.right);
}
}
return result;
}
public <T> List<Node<T>> forwardVerticalWalk(Node<T> root) {
List<Node<T>> result = new ArrayList<>();
forwardProcess(root, result);
return result;
}
public <T> List<Node<T>> symmetricVerticalWalk(Node<T> root) {
List<Node<T>> result = new ArrayList<>();
symmetricProcess(root, result);
return result;
}
public <T> List<Node<T>> backwardVerticalWalk(Node<T> root) {
List<Node<T>> result = new ArrayList<>();
backwardProcess(root, result);
return result;
}
private <T> void forwardProcess(Node<T> root, List<Node<T>> list) {
list.add(root);
if (root.left != null) {
forwardProcess(root.left, list);
}
if (root.right != null) {
forwardProcess(root.right, list);
}
}
private <T> void symmetricProcess(Node<T> root, List<Node<T>> list) {
if (root.left != null) {
symmetricProcess(root.left, list);
}
list.add(root);
if (root.right != null) {
symmetricProcess(root.right, list);
}
}
private <T> void backwardProcess(Node<T> root, List<Node<T>> list) {
if (root.left != null) {
backwardProcess(root.left, list);
}
if (root.right != null) {
backwardProcess(root.right, list);
}
list.add(root);
}
}