Counting nodes in a tree in Java

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

    int count()
    
    {
       int retval = 1;
        if(null != getRightChild()) retval+=getRightChild().count();
        if(null != getLeftChild()) retval+=getLeftChild().count();
        return retval;
    
    }
    

    God I hope I didn't make a mistake.

    EDIT: I did actually.

提交回复
热议问题