psisanon
BAN USERGo on parsing till you get a condition which tells you that the tree isn't sorted
private boolean isTreeBST(Node root) {
if (root == null) return true;
if (root.getLeft() != null &&
root.getValue() < root.getLeft().getValue()) {
return false;
}
if (root.getRight() != null &&
root.getValue() > root.getRight().getValue()) {
return false;
}
if(!isTreeBST(root.getLeft()) ||
!isTreeBST(root.getRight())) {
return false;
}
return true;
}
How about this:
private static HashSet<String> result = new HashSet<String>();
private static int [] inputArray = { 2, 3, 5};
private static int target = 10;
public static void main(String[] args) {
System.out.println("InputArray = " + Arrays.toString(inputArray));
System.out.println("Target = " + target);
for(int i=0; i<inputArray.length; i++) {
checkSum("",i,0);
}
for(String res : result) {
System.out.println(res);
}
}
private static void checkSum(String sofar, int next, int sum) {
if (next >= inputArray.length) return;
if (sum==target) {
char [] arr = sofar.toCharArray();
Arrays.sort(arr);
result.add(String.valueOf(arr));
return;
}
if (sum > target) {
return;
}
checkSum(sofar+Integer.toString(inputArray[next]), next, sum+inputArray[next]);
checkSum(sofar+Integer.toString(inputArray[next]), next+1, sum+inputArray[next]);
}
public static int getSum(String input) {
int result = 0;
String prev="";
for (char ch : input.toCharArray()) {
if (Character.isDigit(ch)) {
if (prev.isEmpty()) {
prev = String.valueOf(ch);
} else {
prev += String.valueOf(ch);
}
} else {
if (!prev.isEmpty()) {
result += Integer.valueOf(prev);
prev = "";
}
}
}
if (!prev.isEmpty()) {
result += Integer.valueOf(prev);
prev = "";
}
return result;
}
Good solution, best solution so far
- psisanon May 17, 2015