Counting nodes in a tree in Java

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

    This is a standard recursion problem:

    count():
        cnt = 1 // this node
        if (haveRight) cnt += right.count
        if (haveLeft)  cnt += left.count
    return cnt;
    

    Very inefficient, and a killer if the tree is very deep, but that's recursion for ya...

提交回复
热议问题