Counting nodes in a tree in Java

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

    You can count the tree by traversing it many ways. Simply preorder traversal, the code would be (based on the functions you defined):

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

提交回复
热议问题