For details about what is recursion and why recursion is inefficient, refer to data structure.
What I want to tell you is: when writing Java code, do not use non-recursive algorithms.
The advantage of recursion is to break down large-scale problems into small-scale problems until they are easy to understand and can be solved immediately.
Recursion may be faster than non-recursion when writing Java code. It may be because the JVM performs algorithm optimization when recursive calls are implemented within the JVM. If you have a better explanation, please tell me (weilai2@163.com)
To this end, I have tested the data below:
The Node Type of the tree is treenode0 (custom), 0.1 million traversal (CPU dual core 2.66G ),
When there are 22 knots, there are 5 layers at the bottom of the tree. Recursive traversal takes 0.188 seconds and non-recursive traversal takes 0.625 seconds.
When there are 40 knots, there are 4 layers at the bottom of the tree. Recursive traversal takes 0.35 seconds, and non-recursive traversal takes 1.13 seconds.
When there are 133 knots, 13 layers are at the bottom of the tree. Recursive traversal takes 1.031 seconds and non-recursive traversal takes 3.625 seconds.
When there are 790 knots, there are 62 layers at the bottom of the tree. Recursive traversal takes 6.56 seconds and non-recursive traversal takes 11.62 seconds.
The main test code is as follows: <br/>/** traverse recursively. recursive Implementation. */<br/> Public static <t extends treenode0 <t> List <t> traverse_recursive (t root, <br/> nodefilter <t> filter, list <t> returnlist) {<br/> If (filter = NULL | filter. test (Root) {<br/> list. add (Root); <br/>}< br/> stack <t> Sons = root. sons; <br/> If (sons! = NULL) {<br/> for (INT I = sons. size ()-1; I> = 0; I --) {<br/> T son = sons. get (I); <br/> traverse_recursive (son, filter, returnlist); <br/>}< br/> return returnlist; <br/>}</P> <p>/** depth first traversal. non-Recursive Implementation. */<br/> Public static <t extends treenode0 <t> List <t> traverse_dft (t root, <br/> nodefilter <t> filter) {<br/> stack <t> ST = new stack <t> (); <br/> St. push (Root); <br/> List <t> List = new Arraylist <t> (); <br/> while (! St. isempty () {<br/> T dad = ST. pop (); <br/> If (filter = NULL | filter. test (DAD) {<br/> list. add (DAD); <br/>}< br/> stack <t> Sons = Dad. sons; <br/> If (sons! = NULL) {<br/> for (INT I = sons. size ()-1; I> = 0; I --) {<br/> T son = sons. get (I); <br/> St. push (son); <br/>}< br/> return list; <br/>}< br/>
End.