Skip to content

Instantly share code, notes, and snippets.

@marta-krzyk-dev
Last active October 27, 2019 12:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marta-krzyk-dev/905ba8edac79c6e7f091724c66a23fa3 to your computer and use it in GitHub Desktop.
Save marta-krzyk-dev/905ba8edac79c6e7f091724c66a23fa3 to your computer and use it in GitHub Desktop.
MinDepthBinaryTree
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;
}
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