Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to end a recursive method when a certain condition is met in Java?

Is there a way to abruptly return to the method that calls the method below when the condition is met? Something similar to a break for loops.

public void createTree(TreeNode tree) throws IOException {
    if (i >= preorder.length) {
        // Leave recursive method
    } else if (preorder[i] == '0') {
        tree.value = '0';
        tree.left = tree.right = null;
        i++;                
    } else {
        tree.value = preorder[i];
        i++;
        tree.left = new TreeNode();
        createTree(tree.left);
        tree.right = new TreeNode();
        createTree(tree.right);
    }
}

Thanks.

like image 979
Jigglypuff Avatar asked Dec 28 '22 21:12

Jigglypuff


2 Answers

You can simply let the method return. Then the recursion will go backwards and the remaining statements will be executed.

like image 77
Osiris76 Avatar answered Feb 16 '23 19:02

Osiris76


You could return a status from the method :

/**
 * @return false if the recursion has been aborted
 */
public boolean createTree(TreeNode tree) throws IOException {
    if (i >= preorder.length) {
        return false;
    } 
    else if (preorder[i] == '0') {
        tree.value = '0';
        tree.left = tree.right = null;
        i++;                
    } 
    else {
        tree.value = preorder[i];
        i++;
        tree.left = new TreeNode();
        if (!createTree(tree.left)) {
            return false;
        };
        tree.right = new TreeNode();
        if (!createTree(tree.right)) {
            return false;
        }
    }
}
like image 38
JB Nizet Avatar answered Feb 16 '23 18:02

JB Nizet