Breaking out of a recursion in java

后端 未结 11 1443
故里飘歌
故里飘歌 2020-12-01 04:23

The recursion is sort of a \'divide and conquer\' style, it splits up while getting smaller (Tree data structure), and I want it to break completely if a violation is found,

11条回答
  •  南方客
    南方客 (楼主)
    2020-12-01 05:18

    Unless recursive calls are being evaluated in parallel, you probably just need to add some logic to check the first recursive call's value prior to making the second (and subsequent, if not a binary tree structure) recursive call.

    public abstract class Tree {
    
        protected abstract boolean headIsViolation();
    
        protected abstract boolean isLeaf();
    
        public Tree getLeft();
    
        public Tree getRight();
    
        // Recursive
        public boolean checkViolation() {
            if(this.isLeaf()) {
                return this.headIsViolation();
            }
    
            // If needed, you could pass some sort of 'calculation state'
            // object through the recursive calls and evaluate the violation
            // through that object if the current node is insufficient
            if(this.headIsViolation()) {
                // Terminate the recursion
                return true;
            }
    
            // Fortunately, Java short-circuits ||
            // So if the left child is in violation, the right child will
            // not even be checked
            return this.getLeft().checkViolation() || this.getRight().checkViolation();
        }
    }
    

提交回复
热议问题