[Leetcode] [Java] Minimum Depth of Binary Tree

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.