@@ -24,10 +24,12 @@ public static void main(String[] args) {
24
24
System .out .println ("Printing the Tree" );
25
25
System .out .println ();
26
26
printByLevel (root );
27
+ System .out .println ();
28
+ System .out .println (getDepth (root ));
27
29
}
28
30
29
31
static Node root ;
30
- int size = 0 ;
32
+ static int size = 0 ;
31
33
32
34
public void addNode (int value ) {
33
35
if (size == 0 ) {
@@ -43,14 +45,18 @@ private Node addNode(Node rootNode, int value) {
43
45
return null ;
44
46
}
45
47
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
+ }
54
60
}
55
61
size ++;
56
62
return rootNode ;
@@ -65,11 +71,19 @@ public Node root() {
65
71
}
66
72
67
73
public boolean isEmpty () {
68
- return size == 0 ;
74
+ return size () == 0 ;
69
75
}
70
76
71
77
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
+ }
73
87
}
74
88
75
89
public boolean isRoot (Node node ) {
@@ -126,8 +140,13 @@ public boolean isLeaf(Node node) {
126
140
return !hasLeft (node ) && !hasRight (node );
127
141
}
128
142
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 ;
131
150
}
132
151
133
152
public static void printInOrder (Node node ) {
0 commit comments