Created
April 25, 2019 06:44
-
-
Save sudipp/13bf79000f682bdd0f7c886bac2de261 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private static int CoverLogic(TreeNode node, Stack<TreeNode> stack, HashSet<TreeNode> covered, int minCamera) | |
{ | |
//if node has any uncovered child, then cover it and it's parent(if any) | |
if ((node.left != null && !covered.Contains(node.left)) || (node.right != null && !covered.Contains(node.right))) | |
{ | |
minCamera++; | |
covered.Add(node); | |
if (stack.Any()) //has parent | |
{ | |
//cover parent too | |
covered.Add(stack.Peek()); | |
} | |
} | |
//if node is root and is not covered, then cover it | |
else if (!stack.Any() && !covered.Contains(node)) | |
{ | |
minCamera++; | |
covered.Add(node); | |
} | |
return minCamera; | |
} | |
public int MinCameraCover(TreeNode root) { | |
int minCamera = 0; | |
//Set contains, list of all coverted nodes | |
HashSet<TreeNode> covered = new HashSet<TreeNode>(); | |
//Iterative - POST Order traversal | |
Stack<TreeNode> stack = new Stack<TreeNode>(); | |
while (root != null || stack.Any()) | |
{ | |
while (root != null) | |
{ | |
stack.Push(root); | |
root = root.left; | |
} | |
TreeNode temp = stack.Peek(); | |
if (temp.right == null) | |
{ | |
temp = stack.Pop(); | |
//Console.Write(temp.val + " "); | |
minCamera = CoverLogic(temp, stack, covered, minCamera); | |
//if the popped elemnt is the right of its parent | |
while (stack.Any() && temp == stack.Peek().right) | |
{ | |
temp = stack.Pop(); | |
//Console.Write(temp.val + " "); | |
minCamera = CoverLogic(temp, stack, covered, minCamera); | |
} | |
} | |
else | |
{ | |
root = temp.right; | |
} | |
} | |
return minCamera; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment