Google onsite - 其中有难题 Remove Extra Edge

参考 https://leetcode.com/discuss/interview-question/358676/Google-or-Remove-Extra-Edge

Given a binary tree, where an arbitary node has 2 parents i.e two nodes in the tree have the same child. Identify the defective node and remove an extra edge to fix the tree.

Example:

Input:
	   1
	  / \
	 2   3
	/ \ /
   4   5

Output:

     1			       1
    / \			      / \
   2   3    or	     2   3
  / \ 			    /   /
 4   5		       4   5

Explanation: We can remove either 3-5 or 2-5.

Solution

public static TreeNode removeEdgeBT(TreeNode root) {
	return removeEdgeBT(root, new HashSet<>());
}

private static TreeNode removeEdgeBT(TreeNode node, Set<TreeNode> seen) {
	if (node == null || !seen.add(node)) return null;
	node.left = removeEdgeBT(node.left, seen);
	node.right = removeEdgeBT(node.right, seen);
	return node;
}

Follow-up 1:
What if the tree is a BST?

Example:

Input:
       3
	  / \
	 2   5
	/ \ /
   1   4

Output:
       3
	  / \
	 2   5
	/   /
   1   4

Explanation: In this case we can only remove 2-4 because if we remove 5-4 the BST will be invalid.

Hint https://leetcode.com/problems/validate-binary-search-tree

Solution

public static TreeNode removeEdgeBST(TreeNode root) {
    return removeEdgeBST(root, null, null);
}

private static TreeNode removeEdgeBST(TreeNode node, Integer min, Integer max) {
    if (node == null) return null;
    if ((min != null && node.val < min) || (max != null && node.val > max)) return null;
    node.left = removeEdgeBST(node.left, min, node.val);
    node.right = removeEdgeBST(node.right, node.val, max);
    return node;
}

Follow-up 2:
What if the tree is an N-ary tree?