return statement not returning control to caller in java -
i trying practice binary trees in java , tried write "ispresent" function. function isn't working if argument (testint
) isn't root node value. entering infinite loop. i'm missing silly thing i'm sure.
public class node { // attributes int value; node leftchild; node rightchild; // constructor node (int value) { this.value = value; } // getter int getvalue() { return value; } boolean ispresent(int testint) { node presentnode = this; while (presentnode != null) { if (presentnode.getvalue() == testint) { return true; } else if (testint < presentnode.getvalue()) { presentnode.leftchild.ispresent(testint); } else { presentnode.rightchild.ispresent(testint); } } return false; } } public static void main(string args[]) { int[] integers = new int[size]; arrays.sort(integers); node binarysearchtree = createbstfromsortedarray(integers, 0, size - 1); if (binarysearchtree.ispresent(testint)) { system.out.println("yes"); } else { system.out.println("no"); } in.close(); } private static node createbstfromsortedarray(int[] integers, int start, int end) { if (end < start) { return null; } int mid = (start + end) / 2; node binarysearchtree = new node(integers[mid]); binarysearchtree.leftchild = createbstfromsortedarray(integers, start, mid - 1); binarysearchtree.rightchild = createbstfromsortedarray(integers, mid + 1, end); return binarysearchtree; }
in ispresent
method, ignoring results of calling ispresent
on left
, right
children. assign left
or right
child presentnode
appropriate.
change
} else if (testint < presentnode.getvalue()) { presentnode.leftchild.ispresent(testint); } else { presentnode.rightchild.ispresent(testint); }
to
} else if (testint < presentnode.getvalue()) { presentnode = presentnode.leftchild; } else { presentnode = presentnode.rightchild; }
Comments
Post a Comment