-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathtraversal.java
More file actions
66 lines (60 loc) · 1.29 KB
/
traversal.java
File metadata and controls
66 lines (60 loc) · 1.29 KB
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
package trees;
import java.util.ArrayList;
import java.util.Queue;
public class traversal {
public void PreOrder(BinaryTreeNode root){
if(root!=null)
{
System.out.println(root.data);
PreOrder(root.left);
PreOrder(root.right);
}
}
public void InOrder(BinaryTreeNode root){
if(root!=null){
InOrder(root.left);
System.out.println(root.data);
InOrder(root.right);
}
}
public void PostOrder(BinaryTreeNode root){
if(root!=null){
PostOrder(root.left);
PostOrder(root.right);
System.out.println(root.data);
}
}
public ArrayList<Integer> levelOrder(BinaryTreeNode root){
ArrayList<Integer> res=new ArrayList<>();
if(root==null)
return res;
sun.misc.Queue<BinaryTreeNode> q=new sun.misc.Queue<>();
q.enqueue(root);
q.enqueue(null);
ArrayList<Integer> curr=new ArrayList<Integer>();
while(!q.isEmpty()){
BinaryTreeNode tmp;
try {
tmp=q.dequeue();
if(tmp!=null){
curr.add(tmp.data);
if(tmp.left!=null)
q.enqueue(tmp.left);
if(tmp.right!=null)
q.enqueue(tmp.right);
}
else
{
res.addAll(curr);
curr.clear();
if(!q.isEmpty())
q.enqueue(null);
}
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return res;
}
}