You are on page 1of 3

Big O, Binary Trees, Self assessment questions Whats my BIG O ?

a) while(i < 4){


i++; }

O( 1) , this will take the same amount of time no matter how elements we had We can just type I++; i++; i++; i++; four times
--------------------------b) for(int i = 0; i < n * n; n+= 31 * Math.pi * Math.sqrt(2110)){ } O(N^2), we have to loop through twice and in the long run the fact that Were not visiting every element (n += 31 * PI *.) is insignificant. ---------------------------c) for(int a = 0; a < n ;a++){ do{ j++; }while(j < n) } O(n), this was a trick question because the inner do, while loop will only execute once J is not reinitialized with every iteration so its not actually O(n)

-------------------------------------------d)
while( i < n){ for( int j = 0; j < n * n; j+=2){ while(k < n){ k++; } } i++; } O(n^3), the outer while is O(n), the inner loop for is O(n^2) and the inner while only happens once --------------------------e) void giganticO(int n ){ if(n == 0) return; else{ giganticO(n/2); } } O(log n), we only work with half our values at every iteration.

Count how many nodes are in my binary tree Write a method that counts how many nodes are a in a BST. For reference, this is how you would do it with a linkedlist: public int size(Node head){ if(head == null) return 0; return 1 + size(head.next); }

We can make it analogous to the linked list version: public int size(Node current){ if(current == null) return 0; else return 1 + size(current.getLeft()) + size(current.getRight()); }

Add up all the values in my binary tree Write a method that adds it up, assume that the data is all ints. For reference, this is how you would do it with a linkedlist: public int total(Node head){ if(head == null) return 0; return head.value + total(head.next); } Again, its going to look like the linkedlist version: public int total(Node current){ if(current == null){ return 0; } return current.getValue() + total(current.getLeft()) + total(current.getRight()); }

Get me the average value of all the nodes in my binary tree If youve done the first two parts, its easy. Total(root) / size(root); Or you can do both at once: public double avg(Node c){ int[] val = new int[2]; avgHelper(root, val); return val[0]/val[1]; } public void avgHelper(BSTNode curr, int[] arr){ if(curr == null){ arr[0] += 0; arr[1] += 0; return; } arr[0] += curr.value;

arr[1] += 1; avgHelper( curr.left, arr); avgHelper( curr.right, arr); } Now compare their big O times? Its still O(n) in both cases.

You might also like