We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
No it is not, this would be a terrible solution if it is part of a multithreaded program other threads might use the tree at same time and assume incorrectly that the tree actually is a tree (since the code introduces cycles). It would also be a terrible solution if you did something more complicated with each node value than just printing them, since if an exception is thrown the tree may no longer be a tree (since it might have one cycle).
While recursive solutions has their own problems (such as heavy use of the call stack) theses problems are local and easier to maintain. Other non-recursive solutions where you introduce temporary data structures (such as stacks) are preferable unless you are running on a system with very strict memory restrictions, but in those cases you would not use Java anyway.
Tree: Preorder Traversal
You are viewing a single comment's thread. Return to all comments →
No it is not, this would be a terrible solution if it is part of a multithreaded program other threads might use the tree at same time and assume incorrectly that the tree actually is a tree (since the code introduces cycles). It would also be a terrible solution if you did something more complicated with each node value than just printing them, since if an exception is thrown the tree may no longer be a tree (since it might have one cycle). While recursive solutions has their own problems (such as heavy use of the call stack) theses problems are local and easier to maintain. Other non-recursive solutions where you introduce temporary data structures (such as stacks) are preferable unless you are running on a system with very strict memory restrictions, but in those cases you would not use Java anyway.