Title:
Given a binary tree, find its minimum depth.
The minimum depth is the number of nodes along, the shortest path from the root node to the nearest leaf node.
Test Instructions:
Given a binary tree, return its minimum height.
The minimum height refers to the number of nodes in the shortest path from the root node to the nearest leaf node.
Algorithm Analysis:
* with Heap
* Similar to the algorithm in Binary Tree level Order traversal
* If there is no self-band in the next layer, exit immediately and return the layer number of the layer
AC Code:
/** * Definition for a binary tree node. * public class TreeNode {* int val, * TreeNode left, * TreeNode right; * TreeNode (int x) {val = x;} *} */public class Solution {public int mindepth (TreeNode root) {int Index=0;boolean flag=false; Arraylist<arraylist<integer>> res=new arraylist<arraylist<integer>> (); arraylist<integer> list= new arraylist<integer> (); Linkedlist<treenode> que = new linkedlist<treenode> (); if (Root==null) return 0; Que.add (root); while (que!=null) {TreeNode tem; int size=que.size (); List.clear (); for (int i=0;i<size;i++) {tem=que.poll (); List.add (Tem.val); if (tem.left==null&&tem.right==null) {flag=true;//If there is no child node of the parent node, just jump out, statistics size break; } if (Tem.left!=null) Que.add (tem.left); if (tem.right!=null) Que.add (tem.right); } res.add (new arraylist<integer> (list)); if (flag) return res.size (); else Index=res.size ();} return index; }}
Copyright NOTICE: This article is the original article of Bo Master, reprint annotated source
[Leetcode] [Java] Minimum Depth of Binary Tree