My clean On) java solution. I get a stackoverflow, but yolo. plserino feedback welcomed.

  • -24
    public class Solution {
        public int countNodes(TreeNode root) {
            if (root == null) {
                return 0;
            int left = countNodes(root.left);
            int right = countNodes(root.right);
            return (1 + left + right);

  • 2

    Your runtime is not O(logn). It's O(n)

  • -1

    oops. my mistake. it runs O(n).

  • 1

    so even this is a totally complete tree, you still need to count all the nodes? I would say it would be better to check whether the last level is full or not.

Log in to reply

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.