Given a tree, sum the values of all of the paths to the root,
// Root is the node that we start with, but also what we continue with.
// Val is used to keep track of the value at the current depth that we
// have to add the current node to.
- (NSInteger)sumOfPaths:(Node<NSNumber *> *)root val:(NSInteger)val {
NSInteger total = 0;
val = (val * 10) + root.val.integerValue;
// If there are any nodes left, then visit them.
if (root.right || root.left) {
if (root.right) {
total += [self sumOfPaths:root.right val:val];
}
if (root.left) {
total += [self sumOfPaths:root.left val:val];
}
} else {
// If there isn't a right or left, then this is a dead end.
// Time to count.
total = val;
}
return total;
}