Intersection of 2 binary trees throws Stack Overflow error

后端 未结 2 1977
清歌不尽
清歌不尽 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

    I don't know the specific problem but there are some issues.

    1. why is "other" passed into the second intersection (it's never used)?
    2. shouldn't you return after you do the insert into the set?
    3. shouldn't you be passing in the local OrderedSet (called result) and inserting into it, rather than global variable?
    4. shouldn't you be comparing the data of root1 and root2 rather then the nodes themselves?
    5. the second return is superfluous
    6. you dereference the roots before you test for null
    7. The initial testing is unnecessary

    Cleaning up those flaws, I get:

    public OrderedSet<E> intersection(OrderedSet<E> other) {
        OrderedSet<E> result = new OrderedSet<E>();
        intersection(result, root, other.root);
        return result;
    }
    
    private void intersection(OrderedSet<E> result, TreeNode root1,
            TreeNode root2) {
        if (root1 == null || root2 == null) {
            return;
        }
        if (root1.data == root2.data) {
            result.insert(root1.data);
        }
        intersection(result, root1.left, root2.left);
        intersection(result, root1.right, root2.right);
    }
    

    I don't know if this will work, but it's closer

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题