Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Commit 880a358

Browse files
Add implementation for a binary tree with insertion and postorder traversal
1 parent ceba214 commit 880a358

File tree

1 file changed

+92
-0
lines changed

1 file changed

+92
-0
lines changed

‎Tree/FirstExample.java

Lines changed: 92 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,92 @@
1+
public class FirstExample {
2+
public static void main(String[] args) {
3+
BinaryTree tree = new BinaryTree();
4+
tree.insertData(8);
5+
tree.insertData(7);
6+
tree.insertData(12);
7+
tree.insertData(15);
8+
tree.insertData(7);
9+
tree.insertData(2);
10+
tree.insertData(5);
11+
12+
// tree.inorder();
13+
// tree.preorder();
14+
tree.postorder();
15+
System.out.println();
16+
17+
}
18+
19+
static class Node {
20+
int data;
21+
Node left;
22+
Node right;
23+
24+
public Node(int data) {
25+
this.data = data;
26+
27+
}
28+
}
29+
30+
public static class BinaryTree {
31+
static Node root;
32+
33+
public static void insertData(int data) {
34+
root = insertRec(root, data);
35+
}
36+
37+
public static Node insertRec(Node root, int data) {
38+
if (root == null) {
39+
root = new Node(data); // create the root first.
40+
} else if (data < root.data) {
41+
root.left = insertRec(root.left, data);
42+
} else if (data > root.data) {
43+
root.right = insertRec(root.right, data);
44+
}
45+
46+
return root;
47+
}
48+
49+
public void inorder() {
50+
inorderRec(root);
51+
}
52+
53+
public static void inorderRec(Node root) {
54+
if (root == null) {
55+
return;
56+
} else {
57+
inorderRec(root.left);
58+
System.out.print(root.data + " ");
59+
inorderRec(root.right);
60+
}
61+
62+
}
63+
64+
//pre order
65+
public static void preorder(){
66+
preorderRec(root);
67+
}
68+
public static void preorderRec(Node root){
69+
if(root == null){
70+
return;
71+
}
72+
System.out.print(root.data + " ");
73+
preorderRec(root.left);
74+
preorderRec(root.right);
75+
}
76+
77+
//post order
78+
public static void postorder(){
79+
postorderRec(root);
80+
}
81+
82+
public static void postorderRec(Node root){
83+
if(root == null){
84+
return;
85+
}
86+
postorderRec(root.left);
87+
postorderRec(root.right);
88+
System.out.println(root.data + " ");
89+
90+
}
91+
}
92+
}

0 commit comments

Comments
(0)

AltStyle によって変換されたページ (->オリジナル) /