CSC301: More Size: Student code [11/30] |
public int size () { if (root == null) return 0; int total = 1 + size (root, 0); return total; // do not count self at the start } private static int size (Node x, int count) { // called when it finds the end int total = count, left = 0, right = 0; // likely can use less space - see about condensing if (x == null) return 0; // return 0 when the node is null - thus finding the end! else { // not at the end when this is called // if left has more, add them up and return them if (x.left != null) { left++; // increment left += size (x.left, left); // should add... } if (x.right != null) { right++; right += size (x.right, right); } // if right has more, add them up and return them } total = left + right; // return result return total; }
Is this correct?
Can it be improved?
Get rid of comments:
public int size () { if (root == null) return 0; int total = 1 + size (root, 0); return total; } private static int size (Node x, int count) { int total = count, left = 0, right = 0; if (x == null) return 0; else { if (x.left != null) { left++; left += size (x.left, left); } if (x.right != null) { right++; right += size (x.right, right); } } total = left + right; return total; }
Unnecessary else. Tighten mutators.
public int size () { if (root == null) return 0; int total = 1 + size (root, 0); return total; } private static int size (Node x, int count) { int total = count, left = 0, right = 0; if (x == null) return 0; if (x.left != null) left += 1 + size (x.left, left); if (x.right != null) right += 1 + size (x.right, right); total = left + right; return total; }
Get rid of some unnecessary variables and put declaration closer to use.
public int size () { if (root == null) return 0; return 1 + size (root, 0); } private static int size (Node x, int count) { if (x == null) return 0; int total = count; if (x.left != null) total += 1 + size (x.left, left); if (x.right != null) total += 1 + size (x.right, right); return total; }
Oops! A bug.
public int size () { if (root == null) return 0; return 1 + size (root, 0); } private static int size (Node x, int count) { if (x == null) return 0; int total = 0; if (x.left != null) total += 1 + size (x.left, left); if (x.right != null) total += 1 + size (x.right, right); return total; }
Notice that the parameter is not used!
public int size () { if (root == null) return 0; return 1 + size (root); } private static int size (Node x) { if (x == null) return 0; int total = 0; if (x.left != null) total += 1 + size (x.left); if (x.right != null) total += 1 + size (x.right); return total; }