-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathKWBinaryTreeExample.java
More file actions
59 lines (51 loc) · 1.43 KB
/
KWBinaryTreeExample.java
File metadata and controls
59 lines (51 loc) · 1.43 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
package com.codinginterview;
public class KWBinaryTreeExample {
public static void main(String[] args) {
System.out.println("Binary Tree Example!");
TreeTraversal t1 = new TreeTraversal();
t1.root = new Node('A');
t1.root.left = new Node('B');
t1.root.right = new Node('C');
t1.root.left.left = new Node('D');
t1.root.left.right = new Node('E');
// Call method
System.out.println("Pre Order Traversal");
t1.prePorderTraversal(t1.root);
System.out.println("\nIn Order Traversal");
t1.inOrderTraversal(t1.root);
System.out.println("\nPost Order Traversal");
t1.postOrderTraversal(t1.root);
}
}
class Node{
char key;
Node left;
Node right;
Node(char key){
this.key = key;
}
}
class TreeTraversal{
Node root;
void prePorderTraversal(Node n){
if(n != null){
System.out.print(n.key + " ");
prePorderTraversal(n.left);
prePorderTraversal(n.right);
}
}
void postOrderTraversal(Node n){
if(n != null){
postOrderTraversal(n.left);
postOrderTraversal(n.right);
System.out.print(n.key + " ");
}
}
void inOrderTraversal(Node n){
if(n != null){
inOrderTraversal(n.left);
System.out.print(n.key + " ");
inOrderTraversal(n.right);
}
}
}