[LeetCode][Java] Minimum Depth of Binary Tree

來源:互聯網
上載者:User

標籤:class   integer   color   最小   targe   ext   get   near   tree   

題目:

Given a binary tree, find its minimum depth.

The minimum depth is the number of nodes along the shortest path from the root node down to the nearest leaf node.

題意:

給定一棵二叉樹。返回它的最小高度。

最小高度是指從根節點到近期的葉子節點的最短路徑中的節點的數目。

演算法分析:

  * 藉助堆

  * 類似《Binary Tree Level Order Traversal》中的演算法

  * 出現下一層無內建的情況,馬上退出,返回該層的層數

AC代碼:

/** * 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;//僅僅要出現父節點無子節點的情況。就直接跳出,統計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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.