CodexBloom - Programming Q&A Platform

Cyclic Recursion in a Tree Traversal Algorithm Causing Infinite Loop in Java

πŸ‘€ Views: 285 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-04
java recursion trees dfs Java

I'm trying to debug I'm prototyping a solution and I've been banging my head against this for hours. I'm currently implementing a recursive tree traversal algorithm in Java using a simple binary tree structure. However, I'm running into an infinite recursion scenario when the tree has cycles (which shouldn't happen in a standard binary tree, but I'm trying to handle it gracefully). I've set up the tree nodes as follows: ```java class TreeNode { int val; TreeNode left; TreeNode right; TreeNode(int x) { val = x; } } ``` The question arises when I try to traverse the tree using a depth-first search (DFS) approach. My current implementation is: ```java public void dfs(TreeNode node) { if (node == null) return; System.out.println(node.val); dfs(node.left); dfs(node.right); } ``` In scenarios where the tree node references might accidentally point back to an ancestor (creating a cycle), this leads to a `StackOverflowError`. To mitigate this, I attempted to keep track of visited nodes using a `HashSet`, but I'm unsure where to integrate this into my recursive method. Here’s what I tried: ```java public void dfs(TreeNode node, Set<TreeNode> visited) { if (node == null || visited.contains(node)) return; visited.add(node); System.out.println(node.val); dfs(node.left, visited); dfs(node.right, visited); } ``` However, I still encounter unexpected behavior when my input tree has cycles. The output is not what I expect, and sometimes it still leads to an infinite loop, causing a `StackOverflowError`. I'm not sure if it's a logic behavior in my cycle detection or an scenario with how I'm passing the `visited` set through the recursive calls. Any suggestions on how to properly implement cycle detection in this recursive traversal? I'm using Java 11, and my tree structure can sometimes have malformed input due to user data. Thanks for your help! My development environment is Windows. Any ideas what could be causing this? Is this even possible? I'm using Java stable in this project. Thanks in advance!