Skip to content

Commit 46d9b90

Browse files
committed
Binary Trees - I : Started
1 parent fdb69eb commit 46d9b90

File tree

3 files changed

+61
-1
lines changed

3 files changed

+61
-1
lines changed

binaryTrees1/BinaryTreeNode.java

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
package binaryTrees1;
2+
3+
public class BinaryTreeNode<T> {
4+
public T data;
5+
public BinaryTreeNode<T> left;
6+
public BinaryTreeNode<T> right;
7+
8+
public BinaryTreeNode(T data) {
9+
this.data = data;
10+
}
11+
}

binaryTrees1/BinaryTreeUse.java

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
package binaryTrees1;
2+
3+
public class BinaryTreeUse {
4+
5+
/* Root -> Left -> Right: Traversal on Binary Tree */
6+
public static void printBinaryTree(BinaryTreeNode<Integer> root) {
7+
// Base Case: if the root is null we just return from that position without doing anything
8+
if (root == null) return;
9+
System.out.println(root.data);
10+
printBinaryTree(root.left);
11+
printBinaryTree(root.right);
12+
}
13+
14+
/* Root -> Left -> Right: Traversal on Binary Tree */
15+
public static void printBinaryTreeDetailed(BinaryTreeNode<Integer> root) {
16+
// Base Case: if the root is null we just return from that position without doing anything
17+
if (root == null) return;
18+
// At this point we only know root is not null
19+
System.out.print(root.data + " : ");
20+
// Printing for the root's left & right data
21+
if (root.left != null) System.out.print("Left -> " + root.left.data + ", ");
22+
if (root.right != null) System.out.print("Right -> " + root.right.data);
23+
System.out.println();
24+
// Now, calling recursively on root's left and root's right
25+
printBinaryTreeDetailed(root.left);
26+
printBinaryTreeDetailed(root.right);
27+
}
28+
29+
public static void main(String[] args) {
30+
// Creating the nodes
31+
var root = new BinaryTreeNode<Integer>(1);
32+
33+
var rootLeft = new BinaryTreeNode<Integer>(2);
34+
var rootRight = new BinaryTreeNode<Integer>(3);
35+
// connecting the nodes
36+
root.left = rootLeft;
37+
root.right = rootRight;
38+
// first part of tree created
39+
40+
// second part is creating
41+
var twoRight = new BinaryTreeNode<Integer>(4);
42+
var threeLeft = new BinaryTreeNode<Integer>(5);
43+
44+
rootLeft.right = twoRight;
45+
rootRight.left = threeLeft;
46+
47+
printBinaryTreeDetailed(root);
48+
}
49+
}

searchingAndSorting/BinarySearch.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -71,4 +71,4 @@ public static void main(String[] args) {
7171
testCases--;
7272
}
7373
}
74-
}
74+
}

0 commit comments

Comments
 (0)