-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathourBinaryTree.java
49 lines (46 loc) · 977 Bytes
/
ourBinaryTree.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
package dataStructure;
import java.util.*;
public class ourBinaryTree<T> {
treeNode<T> root;
public void dfsUtil(treeNode<T> root){
if(root==null ){
return;
}
if(root.visited==true){
return;
}
root.visited = true;
System.out.print(root.data+" ");
dfsUtil(root.left);
dfsUtil(root.right);
}
public void markVisited(treeNode<T> temp){
if(temp==null){
return;
}
temp.visited = false;
markVisited(temp.left);
markVisited(temp.right);
}
public void dfs(){
treeNode<T> temp = this.root;
markVisited(temp);
dfsUtil(temp);
}
public void bfs(){
treeNode<T> temp = this.root;
markVisited(temp);
Queue<treeNode<T>> q = new LinkedList<treeNode<T>>();
q.add(temp);
while(!q.isEmpty()){
treeNode<T> temp2 = q.remove();
if(temp2.left!=null){
q.add(temp2.left);
}
if(temp2.right!=null){
q.add(temp2.right);
}
System.out.print(temp2.data+" ");
}
}
}