Logic operation method based on depth-first traversal and stack recursion

By employing depth-first traversal and stack recursion in logical operations, the problems of operator precedence and complex short-circuit logic judgments in complex nested logical expressions are solved, achieving efficient and modular logical operations and improving the maintainability and performance of the system.

CN121934810APending Publication Date: 2026-04-28LIHONG TECHNOLOGY (SHANGHAI) CO LTD
View PDF 0 Cites 0 Cited by

Patent Information

Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
LIHONG TECHNOLOGY (SHANGHAI) CO LTD
Filing Date
2026-01-16
Publication Date
2026-04-28

AI Technical Summary

Technical Problem

Existing technologies face challenges in handling complex nested logical expressions, including complex operator precedence handling, complex short-circuit logic judgment, high code maintenance costs, and low efficiency in processing dynamically generated or frequently changing logical expressions.

Method used

The logical operation method employs depth-first traversal and stack recursion to represent nested logical expressions as a tree data structure. Through depth-first traversal and stack pushing, combined with the executor module, logical operations are performed to achieve implicit priority management and short-circuit evaluation.

Benefits of technology

It enables efficient calculation of complex nested logical expressions, simplifies code implementation, improves system maintainability and scalability, and enhances computational efficiency.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN121934810A_ABST
    Figure CN121934810A_ABST
Patent Text Reader

Abstract

The invention discloses a logical operation method based on depth-first traversal and stack recursion, and belongs to the technical field of computer logical operation and data processing. The method aims at solving the problems that in the prior art, when a complex nested logic expression is processed, operator priority judgment is complex, short circuit evaluation is difficult to achieve, and code maintainability is poor. The core of the method is that firstly, a nested logic expression to be calculated is abstracted into a tree-shaped or nested array data structure; secondly, a depth-first traversal algorithm is adopted to conduct recursive scanning on the data structure, and in the traversal process, encountered logic operators and basic judgment conditions (calculation factors) or intermediate calculation results of sub-expressions are sequentially pressed into a main stack according to the traversal sequence; when traversal of one sub-expression is completed, an actuator module is automatically triggered; and the executor module pops up a logic operator of the current action range from the main stack.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention relates to the field of computer software and data processing technology, specifically to a logical operation method based on depth-first traversal and stack recursion. Background Technology

[0002] In modern computer science and software engineering practice, evaluating logical expressions is a fundamental and extremely frequent operation. Whether it's conditional statements (if-else, while) in programming languages, complex data filtering rules, rule matching in Business Rule Management Systems (BRMS), or knowledge representation and reasoning in the field of artificial intelligence, the core relies on the precise calculation of logical expressions.

[0003] Currently, the mainstream techniques for processing logical expressions can be broadly categorized into two types. The first type is direct recursive evaluation, typically used in conjunction with an infix parser. This method first parses the string-form expression into an Abstract Syntax Tree (AST) through syntax analysis. The non-leaf nodes of the tree represent logical operators (such as AND, OR, NOT), while the leaf nodes represent basic operands or conditions. Then, the expression is evaluated by performing a post-order traversal or recursive descent on this tree. However, this method faces significant challenges when dealing with complex, deeply nested logical expressions. Specific pain points are as follows:

[0004] Operator precedence and associativity handling is complex: When parsing infix expressions, different logical operators (e.g., AND has higher precedence than OR) and the order of operations defined by parentheses must be explicitly handled. This requires designing complex parsing algorithms, such as the classic Shunting-yard algorithm, or constructing exhaustive rules of grammatical production rules. The code implementation is not only cumbersome but also error-prone, especially when supporting custom operators or dynamically modifying precedence, resulting in extremely high maintenance costs. Short-circuit evaluation is an important optimization feature of logical operations. For example, for the expression `AANDB`, if `A` has already been evaluated as false, the result of the entire expression must be false, and there is no need to evaluate `B`. Similarly, for `AORB`, if `A` is true, there is no need to evaluate `B`. In traditional recursive evaluation models, implementing short-circuit characteristics requires embedding special decision branches in the logic of the recursive function, which tightly couples the evaluation logic with the short-circuit logic, reducing the modularity and readability of the code. As the nesting level deepens, such as `(AORB)AND(CORD)`, the short-circuit logic becomes even more interleaved and complex.

[0005] The second approach involves converting the infix expression to a postfix expression (also known as Reverse Polish Notation, RPN) and then evaluating it using a stack. This method elegantly solves the operator precedence problem, and the evaluation process is relatively simple: scan the postfix expression from left to right, push operands onto the stack when encountered, pop the required number of operands when encountered, perform the calculation, and push the result back onto the stack. However, this method also has inherent limitations: it requires a separate, complete conversion stage, i.e., converting the entire expression from infix to postfix. For dynamically generated or frequently changing logical expressions, this preprocessing overhead can become non-negligible. Furthermore, this method is naturally suitable for linearized string expressions, but for structured (e.g., in JSON or XML format) nested logical rules, forcibly "flattening" them into postfix expressions before calculation is not only circuitous but also loses the clear hierarchical information carried by the original data structure, leading to chaotic processing steps. Especially when dealing with arrays composed of multiple conditions, both performance and readability may degrade. Summary of the Invention

[0006] To address the aforementioned problems, this invention proposes a logical operation method based on depth-first traversal and stack recursion, which more accurately solves the problems mentioned in the background section.

[0007] This invention is achieved through the following technical solutions: The invention is achieved through the following technical solutions:

[0008] A logical operation method based on depth-first traversal and stack recursion includes the following steps: Step 1: Data structuring, representing a nested logical expression containing logical operators and basic judgment conditions as a tree-like or multi-level nested array memory data structure, where logical operators are non-leaf nodes and basic judgment conditions are leaf nodes.

[0009] Step 2: Depth-first traversal and stack push. Initialize a main stack and perform a depth-first traversal on the data structure. During the traversal, when a logical operator node is encountered, push the identifier representing the operator onto the main stack and continue recursively traversing its corresponding child node list. When a basic judgment condition node is encountered, calculate its Boolean value and push the Boolean value as a calculation factor onto the main stack.

[0010] Step 3: Trigger the executor to perform reduction calculation. When all child nodes of a logical operator node have been traversed and processed, an executor module is called. The executor module first pops an element from the top of the main stack as the logical operator to be executed.

[0011] Step 4: Operand collection and operation. The executor module initializes a temporary operand queue, and then cyclically pops elements from the top of the main stack and stores them in the temporary operand queue until all operands belonging to the current logical operator scope have been collected. Then, according to the operation rules of the logical operator, a logical reduction operation is performed on all Boolean values ​​in the temporary operand queue to generate a single Boolean result.

[0012] Step 5: Result backpacking and iteration. Push the Boolean result generated by the logical reduction operation back onto the main stack as a calculation factor for the next level of recursion.

[0013] Repeat steps two through five until the root node of the entire data structure has been traversed. At this point, only one element remains in the main stack, which is the final calculation result of the entire logical expression. Preferably, the data structuring in step one specifically involves parsing the logical expression into a JSON object or an equivalent nested structure of dictionaries and lists.

[0014] Logical operators, such as "and" or "or", serve as keys in the dictionary, and their corresponding values ​​are lists containing subexpressions or basic conditional statements that act as their operands.

[0015] Preferably, the basic judgment condition in step two is an atomic expression, which produces a definite Boolean value (true or false) after calculation; the calculation factor pushed onto the main stack can be either the initial Boolean value obtained from the atomic expression calculation or the result of the subexpression reduction operation pushed back onto the main stack in step five.

[0016] Preferably, the elements stored in the main stack are distinguished by type, including operator type and Boolean value type; in step four, the executor module determines whether the operand collection process has ended by checking the type of the element popped from the main stack. When the popped element is of operator type or encounters a specific scope marker, the operand collection stops.

[0017] Preferably, in step three, the condition for determining that all child nodes of a logical operator node have been traversed is that, in the depth-first traversal algorithm, the loop execution for the sublist of that node has ended, and the stage of backtracking to the parent node is about to begin.

[0018] Preferably, the logical reduction operation in step four, for the "and" operator, is to perform a logical AND operation on all Boolean values ​​in the temporary operand queue to obtain the final AND result; for the "or" operator, it is to perform a logical OR operation on all Boolean values ​​in the temporary operand queue to obtain the final OR result.

[0019] Preferably, the logical reduction operation integrates a short-circuit evaluation mechanism; specifically, when collecting operands for the "and" operator and performing reduction operations, once an operand is encountered that is false, the collection and calculation are stopped immediately, and the false value is directly used as the reduction result of the subexpression, and step five is executed.

[0020] Preferably, the logical reduction operation integrates a short-circuit evaluation mechanism; specifically, when collecting operands for the "or" operator and performing reduction operations, once an operand is found to be true, the collection and calculation are stopped immediately, and the true value is directly used as the reduction result of the subexpression, and step five is executed.

[0021] Preferably, the main stack's data structure is a Last-In-First-Out (LIFO) stack; by combining the recursive characteristics of depth-first traversal with the LIFO characteristics of the main stack, implicit priority management of logical operations at different nesting levels is achieved, that is, sub-expressions with deeper depths are always evaluated first and reduced to a single Boolean value.

[0022] A logic operation system implemented using any of the methods described above, the system comprising: an expression parsing module for executing step one; a traversal and stack pushing module for executing step two; and an executor module for executing steps three, four, and five; the modules working together to calculate the final value of a nested logic expression.

[0023] Beneficial effects: Compared with the prior art, the method provided by the present invention brings the following significant beneficial effects:

[0024] In this invention, by adopting a depth-first traversal strategy, the subexpression with the deepest nesting level is naturally placed in the first position for processing, and its calculation result then becomes the operand of the expression in the previous level. This achieves implicit processing of the operation priority and achieves the effect of correct evaluation without complex infix expression parsing or explicit priority judgment.

[0025] In this invention, by separating the traversal and stack-pushing process from the executor's reduction calculation process, a high degree of modularity and clarity of computational logic is achieved. The traversal process focuses on structure parsing and data preparation, while the executor focuses on pure logical operations. This decoupled design greatly simplifies code implementation, enhances system maintainability and scalability, thereby improving software engineering quality.

[0026] In this invention, the executor module can easily integrate a short-circuit evaluation mechanism when collecting operands and performing reduction calculations. When operating on operands in the temporary queue one by one, once the short-circuit condition is met (e.g., an "and" operation encountering a false value, or an "or" operation encountering a true value), the processing of subsequent operands can be interrupted and the result returned immediately. This achieves the effect of avoiding unnecessary calculations and significantly improving computational efficiency. Attached Figure Description

[0027] Figure 1 The diagram shows a flowchart of the logical operation implementation method of the present invention;

[0028] Figure 2 The diagram shows the main stack structure used in the method of this invention.

[0029] Figure 3 The diagram shown is a schematic flowchart of the actuator module when processing logical operations. Detailed Implementation

[0030] To more clearly and completely illustrate the technical solution of the present invention, the present invention will be further described below with reference to the accompanying drawings.

[0031] Example

[0032] Evaluate a specific nested logical expression.

[0033] The logical expression to be calculated: Assume the input logical expression is represented in JSON format as follows: {or:[{and:[{atom:1},{atom:0}]},{atom:1}]}. This expression is logically equivalent to (true AND false) OR true. Here, {atom:1} represents a basic condition, which evaluates to the boolean value true; {atom:0} represents an expression that evaluates to false.

[0034] System initialization:

[0035] MainStack: Initializes an empty main stack to store operators and calculation factors.

[0036] Iterator: Starts a depth-first traversal, starting from the root node of the expression.

[0037] Executor: A separate module that is invoked at a specific time to perform computations.

[0038] step Current processing node Action description Main stack state (bottom of stack ← top of stack) 1 {or:...} When the OR operator is encountered, it is pushed onto the stack. Preparation begins for processing its subarrays. [or] 2 {and:...} Enter the subarray of `or`, the first element of which is `and`. Push `and` onto the stack. Prepare to process its subarray. [or,and] 3 {atom:1} Enter the subarray of `and`, the first element of which is `atom:1`. Push the computed factor `atom:1` itself onto the stack. [or,and,atom:1] 4 {atom:0} Process the second element, atom:0, of the and subarray. Push the factor atom:0 itself onto the stack. [or,and,atom:1,atom:0] 5 - The subarray of the AND operator has been processed. The executor is then called to process the AND operator. [or, <to be processed and>] 5.1 (Actuator) Pop the top element of the stack, and (operator). [or] 5.2 (Actuator) Create a temporary queue and start a loop to pop the top element from the stack until a non-calculated factor / non-Boolean result is encountered. Temporary queue:[] 5.3 (Actuator) Pop atom:0, get its value (false), and put it into a temporary queue. Temporary queue: [false] 5.4 (Actuator) Pop up atom:1, get its value (true), and put it into a temporary queue. Temporary queue: [false, true] 5.5 (Actuator) Perform an AND operation on all values ​​in the temporary queue: trueandfalse=>false. Temporary queue: [false, true] 5.6 (Actuator) Push the result false back onto the main stack. [or,false] 6 {atom:1} Returning to the subarray of `or`, process the second element `atom:1`. Push the computed factor `atom:1` itself onto the stack. [or,false,atom:1] 7 - The subarray of the OR operator has been processed. The executor is then invoked to process the OR operator. [<To be processed or>] 7.1 (Actuator) Pop the top element from the stack (or operator). [] 7.2 (Actuator) Create a temporary queue and pop the top element from the stack in a loop. Temporary queue:[] 7.3 (Actuator) Pop up atom:1, get its value (true), and put it into a temporary queue. Temporary queue: [true] 7.4 (Actuator) Pop false (the result of the AND operation in the previous step) and put it into a temporary queue. Temporary queue: [true, false] 7.5 (Actuator) Perform an OR operation on all values ​​in the temporary queue: false or true => true. Temporary queue: [true, false] 7.6 (Actuator) Push the final result true back onto the main stack. [true]

[0039] Detailed execution process: The following table combines the... Figure 1 , Figure 2 and Figure 3 The algorithm's execution process is demonstrated step by step through the references.

[0040] Short-circuit evaluation is implemented in this embodiment as follows: In step 5.4 above, if the executor retrieves a false operand from the temporary queue when processing the "AND" operation, it can immediately stop processing other elements (true) in the queue and directly determine that the result of the "AND" operation is false. Similarly, in step 7.4, if the executor retrieves a true operand when processing the "OR" operation, it can immediately determine that the result of the "OR" operation is true, without needing to process subsequent false operands. This mechanism can bring significant performance improvements when the operand list is long and the cost of computing each operand is high.

[0041] Example 2

[0042] This example demonstrates a more complex expression and illustrates the effect of short-circuit evaluation.

[0043] The logical expression to be calculated:

[0044] {and:[{atom:1},{or:[{atom:0},{atom:1}]},{atom:0}]} is logically equivalent to trueAND(falseORtrue)ANDfalse.

[0045] Brief execution process:

[0046] Push in the "and" operator.

[0047] Process the first child element {atom:1}, pushing true onto it. Main stack: [and, true].

[0048] Process the second child element {or:[...]}, pushing the "or" operator onto the stack. Main stack: [and, true, or].

[0049] Enter the sublist of "or", process {atom:0}, and push false.

[0050] Main stack: [and, true, or, false].

[0051] Process {atom:1}, push true. Main stack: [and, true, or, false, true].

[0052] The "or" sublist ends, triggering the executor.

[0053] A "or" message will pop up.

[0054] Collect operands true and false.

[0055] Executing `falseORtrue` returns `true`.

[0056] Push true back onto the main stack. Main stack: [and, true, true].

[0057] Process the third child element {atom:0} of "and", pushing false onto it. Main stack: [and, true, true, false].

[0058] The "and" sublist ends, triggering the executor.

[0059] A "and" message pops up.

[0060] Collect operands false, true, true.

[0061] Short-circuit evaluation: When the executor processes the "and" operation, if it retrieves the first value false from the operand queue, it does not need to check the subsequent two true values ​​and can directly determine that the result of the entire "and" expression is false.

[0062] Push false back onto the main stack. Main stack: [false].

[0063] The traversal is complete, and the final result in the main stack is false.

[0064] As can be seen from the above embodiments, the method of the present invention transforms the complex nested evaluation problem into a clear, linear "traversal-push-reduce" loop. The stack structure perfectly handles the context and scope of the operation, while depth-first traversal ensures the correct order of operations. The combination of the two constitutes a powerful yet concise logic operation engine.

[0065] Finally, it should be noted that the basic concepts have been described above. Obviously, for those skilled in the art, the detailed disclosure above is merely illustrative and does not constitute a limitation of this specification. Although not explicitly stated herein, those skilled in the art may make various modifications, improvements, and corrections to this specification. Such modifications, improvements, and corrections are suggested in this specification, and therefore remain within the spirit and scope of the exemplary embodiments of this specification. Furthermore, this specification uses specific terms to describe embodiments of this specification. For example, "an embodiment," "one embodiment," and / or "some embodiments" refer to a feature, structure, or characteristic associated with at least one embodiment of this specification. Therefore, it should be emphasized and noted that "an embodiment," "one embodiment," or "an alternative embodiment" mentioned twice or more in different locations in this specification do not necessarily refer to the same embodiment. In addition, certain features, structures, or characteristics in one or more embodiments of this specification can be appropriately combined. Moreover, unless expressly stated in the claims, the order of processing elements and sequences, the use of numbers and letters, or other names described in this specification are not intended to limit the order of the processes and methods of this specification.

[0066] Finally, it should be noted that the above descriptions are merely preferred embodiments of the present invention and are not intended to limit the present invention. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art can still modify the technical solutions described in the foregoing embodiments or make equivalent substitutions for some of the technical features. Any modifications, equivalent substitutions, improvements, etc., made within the spirit and principles of the present invention should be included within the protection scope of the present invention.

Claims

1. A logical operation method based on depth-first traversal and stack recursion, characterized in that, Includes the following steps: Step 1: Data structuring. Represent a nested logical expression containing logical operators and basic judgment conditions as a tree-like or multi-level nested array in memory data structure, where logical operators are non-leaf nodes and basic judgment conditions are leaf nodes. Step 2: Depth-first traversal and stack push. Initialize a main stack and perform a depth-first traversal on the data structure. During the traversal, when a logical operator node is encountered, push the identifier representing the operator onto the main stack and continue recursively traversing its corresponding child node list. When a basic judgment condition node is encountered, its Boolean value is calculated, and this Boolean value is pushed onto the main stack as a calculation factor. Step 3: Trigger the executor to perform reduction calculation. When all child nodes of a logical operator node have been traversed and processed, an executor module is called. The executor module first pops an element from the top of the main stack as the logical operator to be executed. Step 4: Operand collection and operation. The executor module initializes a temporary operand queue, and then cyclically pops elements from the top of the main stack and stores them in the temporary operand queue until all operands belonging to the current logical operator scope have been collected. Then, according to the operation rules of the logical operator, a logical reduction operation is performed on all Boolean values ​​in the temporary operand queue to generate a single Boolean result. Step 5: Result backpacking and iteration. Push the Boolean result generated by the logical reduction operation back onto the main stack as the calculation factor for the next level of recursion. Repeat steps 2 to 5 until the root node of the entire data structure is traversed. At this point, only one element remains in the main stack, which is the final calculation result of the entire logical expression.

2. The method according to claim 1, characterized in that, The data structuring in step one specifically involves parsing the logical expression into a JSON object or an equivalent nested structure of dictionary and list; where logical operators, such as "and" or "or", serve as keys in the dictionary, and their corresponding values ​​are lists containing subexpressions or basic judgment conditions that act as their operands.

3. The method according to claim 1, characterized in that, The basic judgment condition in step two is an atomic expression, which produces a definite Boolean value (true or false) after calculation. The calculation factor pushed onto the main stack can be either the initial Boolean value obtained from the atomic expression calculation or the result of the subexpression reduction operation pushed back onto the main stack in step five.

4. The method according to claim 1 or 3, characterized in that, The elements stored in the main stack are distinguished by type, including operator type and Boolean value type. In step four, the executor module determines whether the operand collection process has ended by checking the type of the element popped from the main stack. Operand collection stops when the popped element is of operator type or encounters a specific scope marker.

5. The method according to claim 1, characterized in that, In step three, the condition for determining that all child nodes of a logical operator node have been traversed is that the loop execution of the sublist of that node has ended in the depth-first traversal algorithm, and the stage of backtracking to the parent node is about to begin.

6. The method according to claim 1, characterized in that, The logical reduction operation in step four, for the "and" operator, performs a logical AND operation on all Boolean values ​​in the temporary operand queue to obtain the final AND result; for the "or" operator, performs a logical OR operation on all Boolean values ​​in the temporary operand queue to obtain the final OR result.

7. The method according to claim 6, characterized in that, The logical reduction operation integrates a short-circuit evaluation mechanism; specifically, when collecting operands for the "and" operator and performing reduction operations, once an operand is encountered that is false, the collection and calculation are stopped immediately, and the false value is directly used as the reduction result of the subexpression, and step five is executed.

8. The method according to claim 6, characterized in that, The logical reduction operation integrates a short-circuit evaluation mechanism; specifically, when collecting operands for the "or" operator and performing reduction operations, once an operand is found to be true, the collection and calculation are stopped immediately, and the true value is directly used as the reduction result of the subexpression, and step five is executed.

9. The method according to claim 1, characterized in that, The main stack's data structure is a Last-In-First-Out (LIFO) stack. By combining the recursive characteristics of depth-first traversal with the LIFO characteristics of the main stack, implicit priority management of logical operations at different nesting levels is achieved. That is, sub-expressions with deeper nesting are always evaluated first and reduced to a single Boolean value.

10. A logic operation system implemented using the method of any one of claims 1 to 9, characterized in that, The system includes: an expression parsing module for executing step one; a traversal and stack pushing module for executing step two; and an executor module for executing steps three, four, and five; the modules work together to compute the final value of a nested logical expression.