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.
You can simply let the method return. Then the recursion will go backwards and the remaining statements will be executed.
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;
        }
    }
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With