Additional return statement while finding minimum depth of a Binary Search Tree - recursion

Following is the code that I found online to find the minimum depth of a binary search tree:
public class Solution {
public int minDepth(TreeNode root) {
if(root == null){
return 0;
}
LinkedList<TreeNode> nodes = new LinkedList<TreeNode>();
LinkedList<Integer> counts = new LinkedList<Integer>();
nodes.add(root);
counts.add(1);
while(!nodes.isEmpty()){
TreeNode curr = nodes.remove();
int count = counts.remove();
if(curr.left != null){
nodes.add(curr.left);
counts.add(count+1);
}
if(curr.right != null){
nodes.add(curr.right);
counts.add(count+1);
}
if(curr.left == null && curr.right == null){
return count;
}
}
return 0;
}
}
What I do not understand is the extra return statement at the end- return 0. Why is this needed?

It's for the case where the root isn't null, but it's the only node in the tree (the root is at depth 0). That return statement is needed because if the tree is empty, then something must be returned. It returns 0, because the depth is 0.

Similar to ghostofrasputin, the return statement is there because if the while condition is not met, then there is still a value to return.
Now the more important question, why do we need the last return if the program will never reach that return statement? (which I believe is this case for this)
Even though you are able to tell that the return statement wont be used, the compiler is not sophisticated enough to determine that, so it requires a return statement just in case the while loop is exited.
It's similar to the following code
public boolean getTrueOrFalse() {
if(Math.random() < 1) {
return true;
}
return false;
}
Though we know that this will always return true because Math.random() is always less than 1, the compiler isn't able to figure that out and thus the return statement is required if the if-statement is not met.

Related

sqlite_reset() on an INSERT with RETURNING statement rollback/cancel it

I want to INSERT data in a SQLite table and do this :
sqlite3_stmt *pStmt;
sqlite3_prepare(db,"INSERT INTO table(col2,col3) VALUES (?,?) RETURNING col1;",-1,&pStmt,NULL);
for (int i = 0; i < dataset_length; i++) {
sqlite3_bind_int(pStmt,1,dataset[i].value1);
sqlite3_bind_int(pStmt,2,dataset[i].value2);
switch (sqlite3_step(pStmt)) {
case SQLITE_ROW: {
// Nice! A row has been inserted.
dataset[i].id = sqlite3_column_int(pStmt,0);
} break;
case SQLITE_DONE: {
// No results. What? Return an error.
} return false;
default: {
// Return an error
} return false;
}
// ↓ Problem below ↓
sqlite3_reset(pStmt);
}
//sqlite3_cleanup(pStmt); <- Don't worry about cleanups
return true;
sqlite3_step() always returns SQLITE_ROW and the RETURNING expression works.
If I do a SELECT before the sqlite3_reset(), it returns the freshly inserted row. If I prepare and run the same query after the sqlite3_reset(), my table is empty, the row is vanished.
I tried without the sqlite3_reset() and that works, but I don't understand why and think it's due to the auto-reset feature I OMIT in the Windows build.
Where I am wrong in my SQLite usage?
I finally find out where I was wrong. SQLite mandate to call sqlite_reset() only after receiving an error or SQLITE_DONE.
In my code I only generate a SQLITE_ROW, but I sqlite_reset() before getting a SQLITE_DONE and it cause SQLite to somewhat "reset" the statement and rolling back changes from my point of view.
The correct way is to after a SQLITE_ROW, to call sqlite_step() again that generate a SQLITE_DONE and then sqlite_reset(). That means :
// The way to SQLite with a RETURNING INSERT
for (...) {
// sqlite3_bind...()
sqlite3_step(); // Returns SQLITE_ROW
// sqlite3_column...()
sqlite3_step(); // Returns SQLITE_DONE
sqlite3_reset(); // Returns SQLITE_OK
}
Here is below my fixed code from my question :
sqlite3_stmt *pStmt;
sqlite3_prepare(db,"INSERT INTO table(col2,col3) VALUES (?,?) RETURNING col1;",-1,&pStmt,NULL);
for (int i = 0; i < dataset_length; i++) {
sqlite3_bind_int(pStmt,1,dataset[i].value1);
sqlite3_bind_int(pStmt,2,dataset[i].value2);
switch (sqlite3_step(pStmt)) {
case SQLITE_ROW: {
// Nice! A row has been inserted.
dataset[i].id = sqlite3_column_int(pStmt,0);
// Generate a SQLITE_DONE
if (sqlite3_step(pStmt) != SQLITE_DONE)
// Something went wrong, return an error
return false;
} break;
case SQLITE_DONE: {
// No results. What? Return an error.
} return false;
default: {
// Return an error
} return false;
}
sqlite3_reset(pStmt);
}
//sqlite3_cleanup(pStmt); <- Don't worry about cleanups
return true;
Of course my code imply that there is only 1 row returned by SQLite, adapt your code if SQLite returns more. The rule is that a sqlite_step() must returns a SQLITE_DONE before doing a sqlite_reset().

Function to check whether a binary tree is binary search tree or not?

I attempted writing the following method which tells whether a Binary Tree is Binary Search Tree or not? I pass only half of the test cases. What am I doing wrong?
boolean checkBST(Node root) {
boolean leftflag = false;
boolean rightflag = false;
Node l = root.left;
Node r = root.right;
if(l!=null) {
if(root.data <= l.data) {
leftflag = false;
}
else {
leftflag = true;
checkBST(l);
}
}
if(leftflag == false)
return false;
if(r != null) {
if(root.data >= r.data) {
rightflag = false;
}
else {
rightflag = true;
checkBST(r);
}
}
if(rightflag == false)
return false;
return true;
}
I can see a case where your program could return wrongly false.
Imagine you have a tree with 3 branches deep going as follow :
7
/ \
3 8
\ / \
4 6 9
Your program starts up at 7 (root), creates two boolean at false (leftflag and rightflag), checks if left is null. It isn't. It then checks if the data of left <= the data of right. It is.
So you recursively call your function with a new root node left (3 in the example). Again, it creates your two boolean at false initial value, checks if left node is null. It is ! So it skips the whole if, goes directly to your other if before the return.
// The condition here is respected, there is no left node
// But the tree is an actual search tree, you didn't check right node
// Before returning false.
if(leftflag == false)
return false
What i'd do is
if(l != null)
{
if(root.data<=l.data)
{
return false;
}
else
{
// recursive call here
}
}
if(r != null)
{
// Same as left node here
}
so even if your left node is null, the program still checks for the right node. Hope i helped out a little bit !
Your primary mistake is that you ignore the return value of your recursive calls. For instance:
else {
leftflag = true;
checkBST(l);
}
}
if(leftflag == false)
return false;
If checkBST(l) returns false, you ignore it. You never save the value. Thus, your subsequent check for leftflag is utterly ignorant of the subtree's suitability. Semantically, your routine assumes that all subtrees are BSTs -- you set the flag, recur on the subtree, but don't change the flag. Try this logic:
else
leftflag = checkBST(l)
Now, please get comfortable with Boolean expressions. For instance, testing a Boolean value against a Boolean constant is a little wasteful. Instead of
if (flag == false)
Just check directly:
if (!flag)
Checking a pointer for null is similar in most languages:
if (l)
Finally, don't initialize your flags if you're simply going to set them to the same value as the first action.
Now, your code might appear like this:
boolean leftflag = false;
boolean rightflag = false;
if(l) {
if(root.data > l.data) {
leftflag = checkBST(l);
}
}
if(!leftflag)
return false;
if(r) {
if(root.data < r.data) {
rightflag = checkBST(r);
}
}
if(rightflag == false)
return false;
return true;
}
Now it's a little easier to follow the logic flow. Note that you have a basic failure in your base case: a null tree is balanced, but you return false.
Now, if you care to learn more about logic short-circuiting and boolean expressions, you can reduce your routine to something more like this:
return
(!root.left || // Is left subtree a BST?
(root.data > root.left.data &&
checkBST(root.left)))
&&
(!root.right || // Is right subtree a BST?
(root.data > root.right.data &&
checkBST(root.right)))

Count the number of nodes of a doubly linked list using recursion

Here is what I've done so far:
struct rep_list {
struct node *head;
struct node *tail;
}
typedef rep_list *list;
int length(const list lst) {
if (lst->head == NULL) {
return 0;
}
else {
lst->head = lst->head->next;
return 1 + length(lst);
}
}
This works, but the head of the list the function accepts as a parameter gets changed. I don't know how to fix that.
I'm not allowed to change the function definition so it should always accept a list variable.
Any ideas?
EDIT: I tried to do what Tyler S suggested in the comments but I encountered another problem. If I create a node* variable at the beginning, it should point to lst->head. But then every recursive call to the function changes the value back to lst->head and I cannot move forward.
You don't need a local node: just don't change the list head. Instead, pass the next pointer as the recursion head.
int length(const list lst) {
if (lst->head == NULL) {
return 0;
}
else {
return 1 + length(lst->head-next);
}
}
I see. Okay; this gets a bit clunky because of the chosen representation. You need a temporary variable to contain the remaining list. This iscludes changing the head.
int length(const list lst) {
if (lst->head == NULL) {
return 0;
}
else {
new_lst = new(list)
new_lst->head = lst->head->next;
var result = 1 + length(new_lst);
free(new_lst)
return result
}
}
At each recursion step, you create a new list object, point it to the 2nd element of the current list, and continue. Does this do the job for you?
Although this solution is clunky and I hate it, its the only way I can see to accomplish what you're asking without modifying the method signature. We create a temporary node * as member data of the class and modify it when we start.
struct rep_list {
struct node *head;
struct node *tail;
}
node *temp = NULL;
bool didSetHead = false;
typedef rep_list *list;
int length(const list lst) {
if ((didSetHead) && (lst->head != temp)) {
temp = lst->head;
didSetHead = false;
}
if (temp == NULL) {
didSetHead = true;
return 0;
}
else {
temp = temp->next;
return 1 + length(temp);
}
}
Please note, I haven't tested this code and you may have to play with a bit, but the idea will work.

Issue with Recursive Methods ("missing return statement")

so I have a program that is running a bunch of different recursive methods, and I cannot get it to compile/run. The error is in this method, according to my computer:
public static int fibo(int n)
// returns the nth Fibonacci number
{
if (n==0)
{
return 0;
}
else if (n==1)
{
return 1;
}
else if (n>1)
{
return fibo(n-1) + fibo(n-2);
}
}
I have this method called correctly in my main method, so the issue is in this bit of code.
I think I can help you in this. Add return n; after your else if. Outside of the code but before the last curlicue.
The code will work as long as n ≥ 0 btw; another poster here is right in that you may want to add something to catch that error.
Make sure all possible paths have a return statement. In your code, if n < 0, there is no return statement, the compiler recognizes this, and throws the error.
public static int fibo(int n)
// returns the nth Fibonacci number
{
if (n<=0)
{
return 0;
}
else if (n==1)
{
return 1;
}
else // All other cases, i.e. n >= 1
{
return fibo(n-1) + fibo(n-2);
}
}

how to write mutually recursive functions in Haxe

I am trying to write a simple mutually recursive function in Haxe 3, but couldn't get the code to compile because whichever one of the mutual functions that appears first will report that the other functions in the group is undefined. A minimal example is below, in which mutually defined functions odd and even are used to determine parity.
static public function test(n:Int):Bool {
var a:Int;
if (n >= 0) a = n; else a = -n;
function even(x:Int):Bool {
if (x == 0)
return true;
else
return odd(x - 1);
}
function odd(x:Int):Bool {
if (x == 0)
return false;
else
return even(x - 1);
}
return even(a);
}
Trying to compile it to neko gives:
../test.hx:715: characters 11-14 : Unknown identifier : odd
Uncaught exception - load.c(181) : Module not found : main.n
I tried to give a forward declaration of odd before even as one would do in c/c++, but it seems to be illegal in haxe3. How can one define mutually-recursive functions like above? Is it possible at all?
Note: I wanted to have both odd and even to be local functions wrapped in the globally visible function test.
Thanks,
Rather than using the function myFn() {} syntax for a local variable, you can use the myFn = function() {} syntax. Then you are able to declare the function type signiatures before you use them.
Your code should now look like:
static public function test(n:Int):Bool {
var a:Int;
if (n >= 0) a = n; else a = -n;
var even:Int->Bool = null;
var odd = null; // Leave out the type signiature, still works.
even = function (x:Int):Bool {
if (x == 0)
return true;
else
return odd(x - 1);
}
odd = function (x:Int):Bool {
if (x == 0)
return false;
else
return even(x - 1);
}
return even(a);
}
This works because Haxe just needs to know that even and odd exist, and are set to something (even if it's null) before they are used. We know that we'll set both of them to callable functions before they are actually called.
See on try haxe: http://try.haxe.org/#E79D4

Resources