-
Notifications
You must be signed in to change notification settings - Fork 1
/
Traversal.java
50 lines (38 loc) · 1.23 KB
/
Traversal.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
import java.util.ArrayList;
import java.util.Stack;
// Class used to traverse the node tree.
// It has some functions
// 1. getRoot => return the root node
// 2. preOrderTraversal => Traverse the tree in preorder method (root,left,right)
// 3. preOrder => Set the tree in a array in preorder level.
class Traversal {
Lexical lexer = new Lexical();
Stack<Node> stack = new Stack<>();
private Node root;
Node getRoot() {
return this.root;
}
public void setRoot(Node root) {
this.root = root;
}
void preOrderTraversal() {
int depthOfTree = 0;
if (stack.empty()) {
throw new RuntimeException("Error!! The Stack is empty");
}
Node root = stack.pop();
this.setRoot(root);
preOrder(root, depthOfTree);
}
void preOrder(Node t, int depthOfTree) {
ArrayList<String> elements = new ArrayList<>();
elements.add(t.getToken());
depthOfTree++;
if (t.getLeftChild() != null) {
preOrder(t.getLeftChild(), depthOfTree);
}
if (t.getRightChild() != null) {
preOrder(t.getRightChild(), depthOfTree - 1);
}
}
}