Good day, I'm trying to improve my abilities with Big-O, and I wrote a Java algorithm to print a tree to the console.
public static void printTree(Tree tree){ int height = getHeight(tree); int maxWidth = (int)Math.pow(2, height) - 1; HashMap<Coordinate, Integer> coordinates = getTreeCoordinates(tree, maxWidth/(int)Math.pow(2, 1) + 1, 1, maxWidth); printCoordinatesToConsole(coordinates, maxWidth, height); } static void printCoordinatesToConsole(HashMap<Coordinate, Integer> coordinates, int width, int height){ for (int j = 1; j <= height; j++){ for (int i = 1; i <= width; i++){ if (coordinates.containsKey(new Coordinate(i, j))) System.out.print(coordinates.get(new Coordinate(i, j))); else System.out.print(' '); } System.out.print("n\n"); } } static HashMap<Coordinate, Integer> getTreeCoordinates(Tree tree, int x, int y, int maxWidth){ HashMap<Coordinate, Integer> result = new HashMap<>(); result.put(new Coordinate(x, y), tree.data); if (tree.left == null && tree.right == null){ return result; } else if (tree.left == null){ result.putAll(getTreeCoordinates(tree.right, x+maxWidth/(int)Math.pow(2, y+1) + 1, y+1, maxWidth)); return result; } else if (tree.right == null){ result.putAll(getTreeCoordinates(tree.left, x-maxWidth/(int)Math.pow(2, y+1) - 1, y+1, maxWidth)); return result; } else{ result.putAll(getTreeCoordinates(tree.right, x+maxWidth/(int)Math.pow(2, y+1) + 1, y+1, maxWidth)); result.putAll(getTreeCoordinates(tree.left, x-maxWidth/(int)Math.pow(2, y+1) - 1, y+1, maxWidth)); return result; } } As far as I can tell, the complexity would be based on:
1.Finding tree height O(n)
2.Storing the coordinates for all elements in the hashmap O(n)
3.Printing the coordinates to the screen O(width*height)
Now, since width is 2^height, which in the worst case would be n, does this mean the time complexity is O(n*2^n)? Also, if I were to ignore the printing (or if I were to print directly to the coordinates on the console rather than iterating through all of the width/height), would the complexity then be O(n)
Thank you!