Skip to content

Commit ff41742

Browse files
committed
Binary Tree
1 parent d52bf68 commit ff41742

File tree

2 files changed

+33
-14
lines changed

2 files changed

+33
-14
lines changed

README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -33,7 +33,7 @@ This repository contains various data structures and provide insights about them
3333

3434
**5. Trees**
3535
- [ ] Introduction
36-
- [ ] Binary Tree
36+
- [X] [Binary Tree](../master/src/com/deepak/data/structures/Tree/BinaryTree.java)
3737
- [ ] Binary Search Tree
3838
- [ ] AVL Tree
3939
- [ ] Splay Tree

src/com/deepak/data/structure/Tree/BinaryTree.java

Lines changed: 32 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -24,10 +24,12 @@ public static void main(String[] args) {
2424
System.out.println("Printing the Tree");
2525
System.out.println();
2626
printByLevel(root);
27+
System.out.println();
28+
System.out.println(getDepth(root));
2729
}
2830

2931
static Node root;
30-
int size = 0;
32+
static int size = 0;
3133

3234
public void addNode(int value) {
3335
if (size == 0) {
@@ -43,14 +45,18 @@ private Node addNode(Node rootNode, int value) {
4345
return null;
4446
}
4547
Node newNode = new Node(value);
46-
if (rootNode.left == null) {
47-
rootNode.left = new Node(value);
48-
} else if (rootNode.left != null && newNode.data <= rootNode.data) {
49-
rootNode.left = addNode(rootNode.left, value);
50-
} else if (rootNode.right == null && newNode.data > rootNode.data) {
51-
rootNode.right = new Node(value);
52-
} else if (rootNode.right != null) {
53-
rootNode.right = addNode(rootNode.right, value);
48+
if (newNode.data <= rootNode.data) {
49+
if (rootNode.left != null) {
50+
rootNode.left = addNode(rootNode.left, value);
51+
} else {
52+
rootNode.left = newNode;
53+
}
54+
} else {
55+
if (rootNode.right != null) {
56+
rootNode.right = addNode(rootNode.right, value);
57+
} else {
58+
rootNode.right = newNode;
59+
}
5460
}
5561
size++;
5662
return rootNode;
@@ -65,11 +71,19 @@ public Node root() {
6571
}
6672

6773
public boolean isEmpty() {
68-
return size == 0;
74+
return size() == 0;
6975
}
7076

7177
public int size() {
72-
return size;
78+
return size(root);
79+
}
80+
81+
private int size(Node root) {
82+
if (root == null) {
83+
return 0;
84+
} else {
85+
return (size(root.left)) + 1 + (size(root.right));
86+
}
7387
}
7488

7589
public boolean isRoot(Node node) {
@@ -126,8 +140,13 @@ public boolean isLeaf(Node node) {
126140
return !hasLeft(node) && !hasRight(node);
127141
}
128142

129-
public int getLevel() {
130-
return (int)(Math.log(size) / Math.log(2));
143+
public static int getDepth(Node node) {
144+
if (node == null) {
145+
return 0;
146+
}
147+
int left = getDepth(node.left);
148+
int right = getDepth(node.right);
149+
return left > right ? left + 1 : right + 1;
131150
}
132151

133152
public static void printInOrder(Node node) {

0 commit comments

Comments
 (0)