-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathBSTTraversal.java
49 lines (44 loc) · 1.17 KB
/
BSTTraversal.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
import java.util.*;
class Program {
// O(n) time | O(n) space - where n is the number of nodes in the BST
public static List<Integer> inOrderTraverse(BST tree, List<Integer> array) {
// Write your code here.
if (tree == null) {
return array;
}
inOrderTraverse(tree.left, array);
array.add(tree.value);
inOrderTraverse(tree.right, array);
return array;
}
// O(n) time | O(n) space - where n is the number of nodes in the BST
public static List<Integer> preOrderTraverse(BST tree, List<Integer> array) {
// Write your code here.
if (tree == null) {
return array;
}
array.add(tree.value);
preOrderTraverse(tree.left, array);
preOrderTraverse(tree.right, array);
return array;
}
// O(n) time | O(n) space - where n is the number of nodes in the BST
public static List<Integer> postOrderTraverse(BST tree, List<Integer> array) {
// Write your code here.
if (tree == null) {
return array;
}
postOrderTraverse(tree.left, array);
postOrderTraverse(tree.right, array);
array.add(tree.value);
return array;
}
static class BST {
public int value;
public BST left;
public BST right;
public BST(int value) {
this.value = value;
}
}
}