File tree Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Expand file tree Collapse file tree 1 file changed +34
-0
lines changed Original file line number Diff line number Diff line change
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
+ }
You can’t perform that action at this time.
0 commit comments