i need write 1 method compute total number of edges in binary tree. trying recursion because can computed based on number of nodes - 1, wasn't sure how subtract 1 @ end of recursion. because of that, trying update variable "count" , subtract 1 @ end. wondering if best approach, or if should try way.
public int numofedges(node v){ int count; if(isleaf(v){ count = 0; } else{ count = 1 + numofedges(left(v)) + numofedges(right(v)); } return count - 1; }
i think might easiest accomplish writing 2 different methods, common technique when using recursion:
private int numnodesin(node v) { if (v == null) return 0; return 1 + numnodesin(v.left) + numnodesin(v.right); } public int numedgesin(node v) { return v == null? 0 : numnodesin(v) - 1; }