Every node in binary tree = sum of subtree I wrote this in Java (I know that the brackets don't exactly follow the standard way of doing it in Java - so it looks a bit like C#). But I was wondering how this algorithm is percieved. I have seen some iterative ways of solving the problem - but I thought recursion improves readability here.

Every node in a Binary Tree, has to have the value of it's subtree. 

   8
  /  \
 3    2
/ \
1  2


Would be an example of such a tree. (1+2 = 3 at the bottom, and 1 + 2 + 3 + 2 = 8 at the top). An empty tree is considered 'valid'. 

public boolean isValid()
{
    return isValid(root);
}

public boolean isValid(BinaryNode&lt;E&gt; node)
{
    if (node == null)
        return true;

    int sum = sumOfSub(node.getLeft()) + sumOfSub(node.getRight());

    if (node.getLeft() != null &amp;&amp; node.getRight() != null)
    {
        if ((Integer) node.getData() != sum)
        {
            return false;
        }
    }
    else
        return true;

    return isValid(node.getLeft()) &amp;&amp; isValid(node.getRight());
}

private int sumOfSub(BinaryNode node)
{
    if (node == null) return 0;
    int value = (Integer) node.getData();
    return value + sumOfSub(node.getLeft()) + sumOfSub(node.getRight());
}
This part of your code could probably be simplified


if (node.getLeft() != null &amp;&amp; node.getRight() != null)
{
    if ((Integer) node.getData() != sum)
    {
        return false;
    }
}
else
    return true;



First off, don't do an else statement without curly braces when the corresponding if statement has curly braces, it doesn't follow expected coding practices.

Then you should return early

if (node.getLeft() == null || node.getRight() == null) {
    return true;
} else if ((Integer) node.getData() != sum) {
    return false;
}




As your code is written in the original post it will never hit this statement


return isValid(node.getLeft()) &amp;&amp; isValid(node.getRight());



and will always return true, if (node.getLeft() == null || node.getRight() == null)