Intersection of 2 binary trees throws Stack Overflow error

后端 未结 2 1978
清歌不尽
清歌不尽 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 intersection(OrderedSet other) {
        OrderedSet result = new OrderedSet();
        intersection(result, root, other.root);
        return result;
    }
    
    private void intersection(OrderedSet 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

提交回复
热议问题