Created
May 4, 2024 10:51
-
-
Save tewari2312/57b8edf8d8c16c7495f041d7937f3d8b to your computer and use it in GitHub Desktop.
This file contains hidden or 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
| class MinimumDepthOfBinaryTree { | |
| int minDepth = 0; | |
| int currentDepth = 0; | |
| public static void main(String[] args) { | |
| TreeNode node9 = new TreeNode(9); | |
| TreeNode node15 = new TreeNode(15); | |
| TreeNode node7 = new TreeNode(7); | |
| TreeNode node20 = new TreeNode(20,node15,node7); | |
| TreeNode node3 = new TreeNode(3,node9,node20); | |
| System.out.println(new MinimumDepthOfBinaryTree().minDepth(node7)); | |
| } | |
| public int minDepth(TreeNode root) { | |
| if(root!=null){ | |
| currentDepth++; | |
| if(root.left==null && root.right==null){ | |
| if(minDepth==0) | |
| minDepth = currentDepth; | |
| else | |
| minDepth = Math.min(currentDepth, minDepth); | |
| }else{ | |
| if(root.left!=null) | |
| minDepth(root.left); | |
| if(root.right!=null) | |
| minDepth(root.right); | |
| } | |
| currentDepth--; | |
| } | |
| return minDepth; | |
| } | |
| } | |
| class TreeNode { | |
| int val; | |
| TreeNode left; | |
| TreeNode right; | |
| TreeNode() {} | |
| TreeNode(int val) { this.val = val; } | |
| TreeNode(int val, TreeNode left, TreeNode right) { | |
| this.val = val; | |
| this.left = left; | |
| this.right = right; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment