Last active
October 27, 2019 12:28
-
-
Save marta-krzyk-dev/905ba8edac79c6e7f091724c66a23fa3 to your computer and use it in GitHub Desktop.
MinDepthBinaryTree
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
public class Solution { | |
private int compx; | |
public int MinDepth(TreeNode root) { | |
compx = 0; | |
if (root is null) | |
return 0; | |
Queue queue = new Queue(); | |
queue.Enqueue(new Item(1, root)); | |
Item current; | |
while(queue.Count != 0) | |
{ | |
++compx; | |
current = (Item) queue.Dequeue(); | |
root = current.TreeNode; | |
if (root.left is null && root.right is null) | |
{ | |
Console.WriteLine("Complexity: " + compx); | |
return current.Depth; | |
} | |
else | |
{ | |
if (root.left != null) | |
queue.Enqueue(new Item(current.Depth + 1,root.left)); | |
if (root.right != null) | |
queue.Enqueue(new Item(current.Depth + 1, root.right)); | |
} | |
} | |
return 0; | |
} | |
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
public class Solution | |
{ | |
public int MinDepth(TreeNode root) | |
{ | |
if (root is null) | |
return 0; | |
return MinDepth(root, 1); | |
} | |
private int MinDepth(TreeNode root, int currentDepth) | |
{ | |
if (root is null || (root.left is null && root.right is null)) | |
return currentDepth; | |
else | |
{ | |
++currentDepth; | |
if (root.left is null) | |
return MinDepth(root.right, currentDepth); | |
else if (root.right is null) | |
return MinDepth(root.left, currentDepth); | |
else | |
return Math.Min(MinDepth(root.left, currentDepth), MinDepth(root.right, currentDepth)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment