Skip to content

Commit 9b2ad7e

Browse files
authored
Create MinimumDepthOfBinaryTree.java
1 parent 9aab080 commit 9b2ad7e

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

MinimumDepthOfBinaryTree.java

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,34 @@
1+
/**
2+
* Given a binary tree, find its minimum depth.
3+
* The minimum depth is the number of nodes along the shortest path from the root node
4+
* down to the nearest leaf node.
5+
*/
6+
public class MinimumDepthOfBinaryTree {
7+
public static void main (String[] args){
8+
System.out.println("Minimum depth of the tree is : " + getDepth(getTree()));
9+
}
10+
11+
private static int getDepth(TreeNode root) {
12+
if(root == null) return 0;
13+
if(root.left == null) return getDepth(root.right) + 1;
14+
if(root.right == null) return getDepth(root.left) + 1;
15+
return Integer.min(getDepth(root.left), getDepth(root.right)) + 1;
16+
}
17+
18+
public static class TreeNode {
19+
int val;
20+
TreeNode left;
21+
TreeNode right;
22+
TreeNode(int x) { val = x; }
23+
}
24+
25+
public static TreeNode getTree(){
26+
TreeNode root = new TreeNode(10);
27+
root.left = new TreeNode(5);
28+
root.left.left = new TreeNode(3);
29+
root.right = new TreeNode(15);
30+
root.right.right = new TreeNode(20);
31+
root.right.right.right = new TreeNode(23);
32+
return root;
33+
}
34+
}

0 commit comments

Comments
 (0)