Counting nodes in a tree in Java

前端 未结 15 1760
我寻月下人不归
我寻月下人不归 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:38

    class Tree {
    
      Tree getRightChild() {
        // Assume this is already implemented
      }
    
      Tree getLeftChild() {
        // Assume this is already implemented
      }
    
      int count() {
       return 1 
          + getRightChild() == null? 0 : getRightChild().count()
          + getLeftChild() == null? 0 : getLeftChild().count();
      }
    }
    

提交回复
热议问题