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

Is there a way to suddenly return to a method that calls the method below when the condition is met? Something like 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.

+4
source share
4 answers

You can return the 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; } } } 
+3
source

You can simply return the method. Then the recursion will go backward, and the rest of the statements will be executed.

+7
source

you can throw an exception but it seems "dirty"

0
source

You might want to use runtimeexception, but I don't think this is a good design.

If my recursion went this far, that means it was necessary ... and I would probably use a return

0
source

All Articles