Intersection of 2 binary trees throws Stack Overflow error

后端 未结 2 2014
清歌不尽
清歌不尽 2021-01-27 21:36

I am trying to intersect two binary trees, and create a new binary tree with the nodes that are the same, but the following creates a stackOverflow error. Can anyone help me?

2条回答
  •  轮回少年
    2021-01-27 22:04

    A stack overflow error suggests that there's recursion that's not bottoming out before the stack limit is reached. The chief suspect is the private void intersection method. If the inputs are correct binary trees, then the condition (root1 == null || root2 == null) should be reached at some point -- but this might be a long time for a very large, unbalanced binary tree, or never if the "binary trees" are buggy and have a cycle somewhere. Either case could be a reason for the overflow.

    I'd also point out that the condition if (root1 == root2) in the same method is probably not doing what it's intended to: the parameters root1 and root2 are probably not the same object, so that condition will almost certainly be false. Some other equals() based comparison is probably more appropriate.

提交回复
热议问题