-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathTree.java
More file actions
112 lines (96 loc) · 2.54 KB
/
Tree.java
File metadata and controls
112 lines (96 loc) · 2.54 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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
public class Tree {
// node structure
static class Node {
int data;
Node left;
Node right;
Node(int data) {
this.data = data;
}
}
// create node
static Node create_node(int data) {
return new Node(data);
}
// add parent left child
static void add_left_child(Node parent, Node child) {
parent.left = child;
}
// add parent right child
static void add_right_child(Node parent, Node child) {
parent.right = child;
}
// create tree
static Node create_tree() {
// create root node
Node two = create_node(2);
// create add left child with parent two
Node seven = create_node(7);
add_left_child(two, seven);
// create and right child with parent two
Node nine = create_node(9);
add_right_child(two, nine);
// create and left child with parent seven
Node one = create_node(1);
add_left_child(seven, one);
// create and right child with parent seven
Node six = create_node(6);
add_right_child(seven, six);
// create and right child with parent nine
Node eight = create_node(8);
add_right_child(nine, eight);
// create and left child with parent six
Node five = create_node(5);
add_left_child(six, five);
// create and right child with parent six
Node ten = create_node(10);
add_right_child(six, ten);
// create and left child with parent eight
Node three = create_node(3);
add_left_child(eight, three);
// create and right child with parent eight
Node four = create_node(4);
add_right_child(eight, four);
// return root node
return two;
}
// pre order traversal (root, left, right)
static void pre_order_traversal(Node root) {
// print root node
System.out.println(root.data);
// check left child
if (root.left != null) {
pre_order_traversal(root.left);
}
// check right child
if (root.right != null) {
pre_order_traversal(root.right);
}
}
// post order traversal
static void post_order_traversal(Node root) {
// check left child
if (root.left != null) {
post_order_traversal(root.left);
}
// check right child
if (root.right != null) {
post_order_traversal(root.right);
}
// print root node
System.out.println(root.data);
}
// post order traversal
static void in_order_traversal(Node root) {
// check left child
if (root.left != null) {
in_order_traversal(root.left);
}
// print root node
System.out.println(root.data);
// check right child
if (root.right != null) {
in_order_traversal(root.right);
}
}
}