Created
May 26, 2019 08:10
-
-
Save madhur/cafbc69955261a5d64779a1332b9a66a to your computer and use it in GitHub Desktop.
Minmum depth of a tree
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
| // java.util.* and java.util.streams.* have been imported for this problem. | |
| // You don't need any other imports. | |
| public int minTreeDepth(TreeNode root) { | |
| if (root == null) { | |
| return 0; | |
| } | |
| Queue<TreeNode> currQ = new LinkedList<TreeNode>(); | |
| Queue<TreeNode> nextQ = new LinkedList<TreeNode>(); | |
| currQ.add(root); | |
| int minlevel = 1; | |
| while(!currQ.isEmpty()) { | |
| TreeNode node = currQ.remove(); | |
| if(node.left== null && node.right == null) { | |
| return minlevel; | |
| } | |
| if (currQ.isEmpty()) { | |
| if(node.left!=null) | |
| nextQ.add(node.left); | |
| if (node.right !=null) | |
| nextQ.add(node.right); | |
| while(!nextQ.isEmpty()) { | |
| currQ.add(nextQ.remove()); | |
| } | |
| ++minlevel; | |
| } | |
| } | |
| return minlevel; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment