|
5 | 5 | import static java.lang.System.out; |
6 | 6 |
|
7 | 7 | /** |
8 | | - * Created by IntelliJ IDEA. |
| 8 | + * Basic binary tree functions like put, delete, height, traversals, etc. |
9 | 9 | * |
10 | | - * @author: ramswaroop |
11 | | - * @date: 4/19/15 |
12 | | - * @time: 6:35 PM |
13 | | - * @see: https://www.cs.bu.edu/teaching/c/tree/breadth-first/ |
| 10 | + * @author rampatra |
| 11 | + * @since 4/19/15 |
| 12 | + * @link https://www.cs.cmu.edu/~adamchik/15-121/lectures/Trees/trees.html |
| 13 | + * @link http://typeocaml.com/2014/11/26/height-depth-and-level-of-a-tree/ |
14 | 14 | */ |
15 | 15 | public class BinaryTree<E extends Comparable<E>> extends Tree<E> { |
16 | 16 |
|
@@ -46,10 +46,12 @@ public BinaryNode<E> put(BinaryNode<E> node, E value) { |
46 | 46 | return node; |
47 | 47 | } |
48 | 48 |
|
49 | | - /** |
50 | | - * Traversals. |
51 | | - */ |
52 | 49 |
|
| 50 | + /*********************************** |
| 51 | + * |
| 52 | + * Tree Traversals. |
| 53 | + * |
| 54 | + ***********************************/ |
53 | 55 |
|
54 | 56 | /** |
55 | 57 | * Prints the pre-order traversal of the tree. |
@@ -164,25 +166,28 @@ public void deleteChildren(BinaryNode<E> node) { |
164 | 166 |
|
165 | 167 |
|
166 | 168 | /** |
167 | | - * Return the height of the tree. |
| 169 | + * Height of the tree is the number of edges from the root to its farthest leaf. |
| 170 | + * Note: The height of binary tree with single node is taken as zero. |
168 | 171 | * |
169 | | - * @return |
| 172 | + * @return the height of the tree. |
170 | 173 | */ |
171 | 174 | public int height() { |
172 | 175 | return height(root); |
173 | 176 | } |
174 | 177 |
|
175 | 178 | public int height(BinaryNode<E> node) { |
176 | | - if (node == null) return 0; |
| 179 | + if (node == null || (node.left == null && node.right == null)) { |
| 180 | + return 0; |
| 181 | + } |
177 | 182 |
|
178 | 183 | return Math.max(height(node.left), height(node.right)) + 1; |
179 | 184 | } |
180 | 185 |
|
181 | 186 |
|
182 | 187 | /** |
183 | | - * Returns the number of nodes currently in the tree. |
| 188 | + * Size of tree. |
184 | 189 | * |
185 | | - * @return |
| 190 | + * @return the number of nodes currently in the tree. |
186 | 191 | */ |
187 | 192 | public int size() { |
188 | 193 | return size(root); |
@@ -266,8 +271,15 @@ public static void main(String[] a) { |
266 | 271 | bt.put(6); |
267 | 272 | bt.put(7); |
268 | 273 | bt.put(8); |
| 274 | + |
| 275 | + out.print("BFS: "); |
269 | 276 | bt.breadthFirstTraversal(); |
270 | | - out.println(); |
| 277 | + out.print("\nPre Order: "); |
| 278 | + bt.preOrder(); |
| 279 | + out.print("\nIn Order: "); |
271 | 280 | bt.inOrder(); |
| 281 | + out.print("\nPost Order: "); |
| 282 | + bt.postOrder(); |
| 283 | + out.println("\nHeight of tree: " + bt.height()); |
272 | 284 | } |
273 | 285 | } |
0 commit comments