Repository navigation
Expand file tree
/
Copy pathBinaryTreeExtraEdgeRemoveRecursion.java
More file actions
76 lines (56 loc) · 1.77 KB
/
Copy pathBinaryTreeExtraEdgeRemoveRecursion.java
File metadata and controls
76 lines (56 loc) · 1.77 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
package com.abn.dsalgos.algo.DFS;
import com.abn.dsalgos.utils.MyTreeNode;
import java.util.HashSet;
import java.util.Set;
/*
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.
1
/ \
2 3 =>
/ \ /
4 5
1 1
/ \ / \
2 3 or 2 3
/ \ / /
4 5 4 5
*/
public class BinaryTreeExtraEdgeRemoveRecursion {
MyTreeNode<Integer> result = null;
public MyTreeNode<Integer> removeExtraNode(MyTreeNode<Integer> root) {
// DFS and Store the visited nodes in hashset.
// Duplicate addition returns false and store that node as null
Set<MyTreeNode<Integer>> hs = new HashSet<>();
if (root == null) {
return null;
}
removeNode(root);
return result;
}
private void removeNode(MyTreeNode<Integer> root) {
if (root == null) {
return;
}
if(root.left != null && root.left.isVisited) {
result = root.left;
root.left = null;
}
if(root.right != null && root.right.isVisited) {
result = root.right;
root.right = null;
}
removeNode(root.left);
root.isVisited = true;
removeNode(root.right);
}
public static void main(String[] args) {
MyTreeNode<Integer> root = new MyTreeNode<>(1);
root.left = new MyTreeNode<>(2);
root.right = new MyTreeNode<>(3);
root.left.left = new MyTreeNode<>(4);
root.left.right = new MyTreeNode<>(5);
root.right.left = root.left.right;
new BinaryTreeExtraEdgeRemoveRecursion().removeExtraNode(root);
}
}