66
77/**
88 * Basic binary tree functions like put, delete, height, traversals, etc.
9+ * An example of a binary tree:
10+ *
11+ * 5 ------> depth 0, level 1 (depth + 1)
12+ * / \
13+ * 3 8 -----> depth 1, level 2
14+ * / \ / \
15+ * 2 4 9 7 ----> depth 2, level 3
16+ *
17+ * Root of the tree: 5
18+ * Height: 2
919 *
1020 * @author rampatra
1121 * @since 4/19/15
@@ -113,11 +123,12 @@ public void postOrder(BinaryNode<E> node) {
113123 * first, before moving to the next level neighbors. See {@link BFSUsingQueue}
114124 * for a O(n) solution.
115125 * <p>
116- * Time complexity: O(n ^2)
126+ * Time complexity: O(h ^2) where, h is the height of the tree
117127 */
118128 public void breadthFirstTraversal () {
119- // assuming level starts at zero
120- for (int level = 0 ; level < height (root ); level ++) {
129+ int height = height (root );
130+ // assuming level starts at one
131+ for (int level = 1 ; level <= height + 1 ; level ++) {
121132 printLevel (root , level );
122133 }
123134 }
@@ -126,9 +137,9 @@ public void printLevel(BinaryNode<E> node, int level) {
126137 if (node == null ) return ;
127138
128139 // print the starting node
129- if (level == 0 ) {
140+ if (level == 1 ) {
130141 printValue (node );
131- } else { // print the neighbour nodes
142+ } else { // print the immediate child nodes
132143 printLevel (node .left , level - 1 );
133144 printLevel (node .right , level - 1 );
134145 }
0 commit comments