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 tree of two forks. Returns the minimum height of it.
The minimum height refers to the number of nodes in the shortest path from the root node to the recent 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, 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;//only occurs where the parent node has no child nodes. 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; }}
[Leetcode] [Java] Minimum Depth of Binary Tree