Dev102.com programming challenge #9

| | Comments (0)

Programming challenge #9 has been posted at dev102.com. I think that this is about the shortest solution possible.

I initially did this recursively, but I needed two functions: one for the base case using the root and one for all other cases. Here, I just set up the preconditions in variables outside the loop and iterate over the left and right nodes. Which node is second last depends upon whether we went left or right in the last iteration: if left, then the current; if right, then the parent.

Node secondLast(Node root)
{
 boolean wentRight = true;
 Node parent = NULL, current = root;
 while (current->left && current->right)
 {
  parent = current;
  wentRight = (current->right != NULL);
  current = wentRight ? current->right : current->left;
 }
 return (wentRight ? parent : current);
}

I suppose I could be perverse and write the loop with a body of a single line, assigning to parent, wentRight, and current within a single ternary operator statement:

  current = (wentRight = ((parent = current)->right != NULL)) ?
   current->right : current->left;

I think that's a bit obscure just for the sake of brevity.




2008-06-24: I could even drop the wentRight variable and use the parent variable to record which way we went:

 while (current->left && current->right)
 {
  parent = (current->right != NULL) ? current : NULL;
  current = (parent == NULL) ? current->right : current->left;
 }
 return (parent != NULL) ? parent : current;

Now we're down to a loop with just two variables. I don't think I can make the code shorter and simpler than that.

Leave a comment

About this Entry

This page contains a single entry by Hugh Brown published on June 23, 2008 11:29 PM.

Ultimate Code Kata was the previous entry in this blog.

The website's down is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.