Counting nodes in a tree in Java

前端 未结 15 1677
我寻月下人不归
我寻月下人不归 2020-12-03 00:03

First of all, I swear this is not homework, it\'s a question I was asked in an interview. I think I made a mess of it (though I did realise the solution requires recursion).

15条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-03 00:23

    I like this better because it reads:

    return count for left + count for rigth + 1

      int count() {
          return  countFor( getLeftChild() ) + countFor( getRightChild() ) + 1;
      }
      private int countFor( Tree tree )  { 
           return tree == null ? 0 : tree.count();
      }
    

    A little more towards literate programming.

    BTW, I don't like the getter/setter convention that is so commonly used on Java, I think a using leftChild() instead would be better:

      return countFor( leftChild() ) + countFor( rightChild() ) + 1;
    

    Just like Hoshua Bloch explains here http://www.youtube.com/watch?v=aAb7hSCtvGw at min. 32:03

    If you get it rigth your code reads...

    BUT, I have to admit the get/set convention is now almost part of the language. :)

    For many other parts, following this strategy creates self documenting code, which is something good.

    Tony: I wonder, what was your answer in the interview.

提交回复
热议问题