LeetCode – Count Complete Tree Nodes (Java)

Given a complete binary tree, count the number of nodes.


Steps to solve this problem:
1) get the height of left-most part
2) get the height of right-most part
3) when they are equal, the # of nodes = 2^h -1
4) when they are not equal, recursively get # of nodes from left&right sub-trees



Time complexity is O(h^2).

Java Solution

public int countNodes(TreeNode root) {
        return 0;
    int left = getLeftHeight(root)+1;    
    int right = getRightHeight(root)+1;
        return (2<<(left-1))-1;
        return countNodes(root.left)+countNodes(root.right)+1;
public int getLeftHeight(TreeNode n){
    if(n==null) return 0;
    int height=0;
        n = n.left;
    return height;
public int getRightHeight(TreeNode n){
    if(n==null) return 0;
    int height=0;
        n = n.right;
    return height;
Category >> Algorithms >> Interview  
If you want someone to read your code, please put the code inside <pre><code> and </code></pre> tags. For example:
String foo = "bar";

  1. Martingalemsy on 2015-6-15

    how to calculate complexity here?

  2. David on 2015-6-18

    In the worst case, you will have to keep making recursive calls to the bottom-most leaf nodes (e.g. last level only have one single node). So you end up calling countNodes() h times. Each time, you will have to do traversals along the left and right edges. At level h, you iterate zero times (no child). At level h – 1, you iterate once (one child). And so on. So that is 0 + 1 + 2 + … + h steps just to compute the left edges, which is h(1 + h)/2 = O(h^2).

    The space complexity will just be the size of the call stack, which is O(h).

  3. me on 2015-7-4


  4. my on 2015-9-19

    what will happen if 6 is not on the tree?

  5. Simon Zhu on 2015-12-19

    if 6 is not in the tree in the first picture, then the tree will not be complete. Hence, will not be a complete binary tree.

  6. Avinash Sharma on 2016-9-19

    recursive approach, may be it is expensive though but very easy and straight forward:
    it fails the online test saying time limit exceeded as it is visiting all the nodes so the optimal solution is up this is just a trivial one

    public int countNodes(TreeNode root) {

    if(root == null){
    return 0;

    return 1 + countNodes(root.left) + countNodes(root.right);

Leave a comment