patternjavaMinor
Every node in binary tree = sum of subtree
Viewed 0 times
nodeeverybinarysubtreesumtree
Problem
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.
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'.
Every node in a Binary Tree, has to have the value of it's subtree.
8
/ \
3 2
/ \
1 2Would 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 node)
{
if (node == null)
return true;
int sum = sumOfSub(node.getLeft()) + sumOfSub(node.getRight());
if (node.getLeft() != null && node.getRight() != null)
{
if ((Integer) node.getData() != sum)
{
return false;
}
}
else
return true;
return isValid(node.getLeft()) && 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());
}Solution
This part of your code could probably be simplified
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
As your code is written in the original post it will never hit this statement
and will always
if (node.getLeft() != null && 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()) && isValid(node.getRight());and will always
return true, if (node.getLeft() == null || node.getRight() == null)Code Snippets
if (node.getLeft() != null && node.getRight() != null)
{
if ((Integer) node.getData() != sum)
{
return false;
}
}
else
return true;if (node.getLeft() == null || node.getRight() == null) {
return true;
} else if ((Integer) node.getData() != sum) {
return false;
}return isValid(node.getLeft()) && isValid(node.getRight());Context
StackExchange Code Review Q#98682, answer score: 2
Revisions (0)
No revisions yet.