Skip to content

Instantly share code, notes, and snippets.

@jargnar
Last active March 21, 2017 11:27
Show Gist options
  • Save jargnar/df3a7b7eeb10aeb2ea8544b50faacdf4 to your computer and use it in GitHub Desktop.
Save jargnar/df3a7b7eeb10aeb2ea8544b50faacdf4 to your computer and use it in GitHub Desktop.
Minimum Depth of a Binary Tree
/**
* Created by suhas on 21/03/17.
*/
class BinaryTree<T> {
class Node<T> {
T val;
BinaryTree left;
BinaryTree right;
Node(T val, BinaryTree left, BinaryTree right) {
this.val = val;
this.left = left;
this.right = right;
}
}
Node root;
BinaryTree(T val) {
this.root = new Node(val, null, null);
}
int minDepth(BinaryTree tree) {
if (tree == null) {
return 0;
}
else if (tree.root.left == null && tree.root.right == null) {
return 1;
}
else if (tree.root.right == null) {
return minDepth(tree.root.left) + 1;
}
else if (tree.root.left == null) {
return minDepth(tree.root.right) + 1;
}
return Math.min(minDepth(tree.root.left), minDepth(tree.root.right)) + 1;
}
}
public class BinaryTreeMinDepth {
public static void main(String[] args) {
BinaryTree tree = new BinaryTree(1);
tree.root.left = new BinaryTree(2);
tree.root.left.root.left = new BinaryTree(4);
tree.root.left.root.right = new BinaryTree(5);
tree.root.right = new BinaryTree(3);
tree.root.right.root.right = new BinaryTree(7);
tree.root.right.root.right.root.left = new BinaryTree(6);
System.out.println(tree.minDepth(tree));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment