简体   繁体   中英

Count number of nodes in binary tree in Java

static int sum=0;
    public static int size(TreeNode root){
        if(root==null)
        return sum;
        sum++;
        sum=size(root.left);
        sum=size(root.right);
        return sum;
    }

We have to just complete the function "size" which counts the number of nodes in binary tree. I have written the above code. It is giving wrong answer for some testcases. Please explain what is wrong in above code.

Here:

sum=size(root.left);
sum=size(root.right);

You are computing two sums, to then throw away the first one!

You could go: return size(root.left)+size(root.right) + 1 instead.

There is also no point in using a static field sum here. If at all, that should be a local variable within that recursive method! Respectively: simply return 0 for null, otherwise use the return I provided here. There is no need to for that sum variable in the first place!

You have not set sum correctly when get data from child node

    sum += size(root.left);
    sum += size(root.right);

I would advice you not use a global static variable to get the value when you want to do it recursively

    static int sum=0;
    public static int size(TreeNode root){
        if(root==null)
        return 0;
        int cnt = 0;
        cnt++;
        cnt += size(root.left);
        cnt += size(root.right);
        return cnt;
    }

Try something like this:

public static int size(final TreeNode node)
{
    if (null == node ) return 0;
    return 1 + size( node.left ) + size( node.right );
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM