public static int countTrees(int numNodes)
{
if (numNodes <= 1)
{
return 1;
}
int sum = 0;
for (int i = 1; i <= numNodes; i++)
{
int countLeftTrees = countTrees(i - 1);
int countRightTrees = countTrees(numNodes - 1);
sum = sum + (countLeftTrees * countRightTrees);
}
return sum;
}
9.Print all nodes within a range in a binary search tree
L -> V -> R
public static void printRange(Node<Integer> root, int low, int high)
{
if (root == null)
{
return;
}
if (low <= root.getData())
{
printRange(root.getLeftChild(), low, high);
}
if (low <= root.getData() && root.getData() <= high)
{
System.out.println(root.getData());
}
if (high > root.getData())
{
printRange(root.getRightChild(), low, high);
}
}
10.Check if a binary search tree
public static boolean isBinarySearchTree(Node<Integer> root, int min, int max)
{
if (root == null)
{
return true;
}
if (root.getData() <= min || root.getData() > max)
{
return false;
}
return isBinarySearchTree(root.getLeftChild(), min, root.getData()) &&
isBinarySearchTree(root.getRightChild(), root.getData(), max)
}
11.Path sum
public static boolean hasPathSum(Node<Integer> root, int sum)
{
if (root.getLeftChild() == null &&
root.getRightChild() == null)
{
return sum == root.getData();
}
int subSum = sum - root.getData();
if (root.getLeftChild() != null &&
hasPathSum(root.getLeftChild(), subSum))
{
return true;
}
if (root.getRightChild() != null &&
hasPathSum(root.getRightChild(), subSum))
{
return true;
}
return false;
}