Counting nodes in a tree in Java

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

    I did it by preorder recurssion. Altough it doesn't exactly follow the interview format by using localRoot, but I think you get the idea.

    private int countNodes(Node localRoot, int count) {
        if (localRoot == null) 
            return count;     
        count++; // Visit root
        count = countNodes(localRoot.left, count); // Preorder-traverse (left)
        count = countNodes(localRoot.right, count); // Preorder-traverse (right)
        return count;
    }
    
    public int countNodes() {
       return countNodes(root, 0);
    }
    

提交回复
热议问题