-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTraversals.java
98 lines (90 loc) · 2.86 KB
/
Traversals.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
import java.util.List;
import java.util.ArrayList;
import java.util.LinkedList;
/**
* Your implementation of the pre-order, in-order, and post-order
* traversals of a tree.
*/
public class Traversals<T extends Comparable<? super T>> {
/**
* DO NOT ADD ANY GLOBAL VARIABLES!
*/
/**
* Given the root of a binary search tree, generate a
* pre-order traversal of the tree. The original tree
* should not be modified in any way.
*
* This must be done recursively.
*
* Must be O(n).
*
* @param <T> Generic type.
* @param root The root of a BST.
* @return List containing the pre-order traversal of the tree.
*/
public List<T> preorder(TreeNode<T> root) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
ArrayList<T> list = new ArrayList<T>();
traversePreorder(root, list);
return list;
}
/**
* Given the root of a binary search tree, generate an
* in-order traversal of the tree. The original tree
* should not be modified in any way.
*
* This must be done recursively.
*
* Must be O(n).
*
* @param <T> Generic type.
* @param root The root of a BST.
* @return List containing the in-order traversal of the tree.
*/
public List<T> inorder(TreeNode<T> root) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
ArrayList<T> list = new ArrayList<T>();
traverseInorder(root, list);
return list;
}
/**
* Given the root of a binary search tree, generate a
* post-order traversal of the tree. The original tree
* should not be modified in any way.
*
* This must be done recursively.
*
* Must be O(n).
*
* @param <T> Generic type.
* @param root The root of a BST.
* @return List containing the post-order traversal of the tree.
*/
public List<T> postorder(TreeNode<T> root) {
// WRITE YOUR CODE HERE (DO NOT MODIFY METHOD HEADER)!
ArrayList<T> list = new ArrayList<T>();
traversePostorder(root, list);
return list;
}
private void traversePreorder(TreeNode<T> node, List<T> list) {
if (node != null) {
list.add(node.getData());
traversePreorder(node.getLeft(), list);
traversePreorder(node.getRight(), list);
}
}
private void traverseInorder(TreeNode<T> node, List<T> list) {
if (node != null) {
traverseInorder(node.getLeft(), list);
list.add(node.getData());
traverseInorder(node.getRight(), list);
}
}
private void traversePostorder(TreeNode<T> node, List<T> list) {
if (node != null) {
traversePostorder(node.getLeft(), list);
traversePostorder(node.getRight(), list);
list.add(node.getData());
}
}
}